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.


Entity Framework Core Code First

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

Installing Entity Framework Core

Next, add Entity Framework Core packages to your project using the NuGet Package Manager or the .NET CLI.


NuGet - Entity Framework Core Code First
.NET CLI:

  • dotnet add package Microsoft.EntityFrameworkCore.SqlServer
  • dotnet add package Microsoft.EntityFrameworkCore.Tools

Defining the Domain Model

Now, let's define our domain model classes. For this example, let's create a simple Product class:
public class Product
{
    public int ProductId { getset; }
    public string ProductCode { getset; }
    public string Name { getset; }
    public decimal Price { getset; }
    public decimal Weight { getset; }
}
Creating the DbContext

Next, we need to create a DbContext class that represents a session with the database and allows us to query and save instances of our domain classes:
using Microsoft.EntityFrameworkCore;
 
public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
 
    public DbSet<Product> Products { getset; }
}
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")));
Running Migrations

Entity Framework Core provides a set of tools for managing database migrations. Let's run the migration to create the database schema based on our domain model:
  • dotnet ef migrations add InitialCreate --project {your_projectName_here}
  • dotnet ef database update --project {your_projectName_here}

If you are facing the cretificate chain issue while connecting to database with the above commands, you might need to append the encrypt=false to your connection string.

One you run the migration commads, you can see the database table get created in your database which is mentioned in your connection string as shown below:

Database - Entity Framework Core Code First

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.

Using EF Core in Controllers

Finally, let's use EF Core in our ASP.NET Core controllers to perform CRUD operations on our Product entity:
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. 

Also EF Core provides many more features for advanced scenarios like querying with LINQ, handling relationships, and optimizing performance. This artile should give you a solid foundation for using Entity Framework Core Code First in your ASP.NET Core projects. 

Thanks for reading artile, Happy Coding!

No comments:

Powered by Blogger.