Entity Framework Core Code First – Step by Step Guide for ASP.NET Core
In our previous article we have learned about Entity Framework Core Database First approach. In this article we will go in detail about the Entity Framework Core Code First approach.
Entity Framework Core (EF Core) is a powerful and lightweight Object-Relational Mapping (ORM) framework that allows developers to work with databases using .NET objects. In this guide, we'll explore the Code First approach in EF Core, which enables developers to define their domain model using plain C# or VB.NET classes, and then automatically generate the database schema based on these classes.
Setting up the ASP.NET Core Project
First, let's create a new ASP.NET Core project in Visual Studio or using the .NET CLI:
- dotnet new web -n EFCoreCodeFirstApproach
Next, add Entity Framework Core packages to your project using the NuGet Package Manager or the .NET CLI.
- dotnet add package Microsoft.EntityFrameworkCore.SqlServer
- dotnet add package Microsoft.EntityFrameworkCore.Tools
public class Product { public int ProductId { get; set; } public string ProductCode { get; set; } public string Name { get; set; } public decimal Price { get; set; } public decimal Weight { get; set; } }Creating the DbContext
using Microsoft.EntityFrameworkCore; public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Product> Products { get; set; } }Configuring the Database Connection
Configure the database connection in the Program.cs file:
//add DbContext Service builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
- dotnet ef migrations add InitialCreate --project {your_projectName_here}
- dotnet ef database update --project {your_projectName_here}
If your class models got modified and to bring the new changes to your database tables, you will need to run the above same commands by changing the add migration name from InitialCreate to different.
public class ProductController : Controller { private readonly ApplicationDbContext _context; public ProductController(ApplicationDbContext context) { _context = context; } public IActionResult Index() { return View(); } [HttpGet] public IActionResult GetAllProducts() { var products = _context.Products.ToList(); return Ok(products); } [HttpPost] public IActionResult CreateProduct([FromBody] Product product) { _context.Products.Add(product); _context.SaveChanges(); return GetAllProducts(); } }In this artile, we've covered the fundamentals of using Entity Framework Core Code First approach in ASP.NET Core. We've defined our domain model, created a DbContext, configured the database connection, run migrations, and performed CRUD operations using EF Core in our controllers.
No comments: