Advertisement

Advertisement

Create CRUD Operation Using Asp.net Core 6 EF 6 Code First Approach

Create CRUD Operation Using Asp.net Core 6 EF 6 Code First Approach


Step 1. Create Asp.net Mvc Core6 Project.

Step 2. Right Click on Project select Edit Project Fie (thru this we can get .net & EF  version & also                we can direct paste Package, Packages below, we just copy n paste it)
  <ItemGroup>
    <!--<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.8" />-->
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.8" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.8">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.14" />
 </ItemGroup>

Step 3. Right Click on Model create model Course.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebApplication3.Models
{
    public class Course
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [StringLength(50)]
        [Display(Name ="Course Name")]
        public String Name { get; set; }

        [NotMapped]
        public DateTime StartDate { get; set; }= DateTime.Now;
    }
}

Step 4. Right Click on Project create Data folder then in this folder create class file which                                    ApplicationDbContext.cs

using Microsoft.EntityFrameworkCore;
using WebApplication3.Models;

namespace WebApplication3.Data
{
    public class ApplicationDbContext: DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
            
        }
        public DbSet<Course> Courses { get; set; }
    }
}

Step 5. Create a connection string in appsettings.json Just copy n paste code below

,
  "ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-JJDFFJA\\SQLEXPRESS; Database=Db_Course; Trusted_Connection=true; MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=True"
  }

Step 6. Add a services in Program.cs file code below

builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

Step 7. Open PMC(Package Manager Console) just type below line

Add-Migration AddDbCourse (add-migration ye as it is type kre name kuch v type ex. addsa, a, ea2 etc)
update-database

Step 8. Create Controller n then run .


Create CRUD Operation Using Asp.net Core 6 EF 6 Code First Approach Create CRUD Operation Using Asp.net Core 6 EF 6 Code First Approach Reviewed by Rikesh on July 01, 2023 Rating: 5

No comments:

Powered by Blogger.