Entity Framework Core (EF Core) is a lightweight, extensible, open-source version of the Entity Framework, designed for .NET Core applications. It is an Object-Relational Mapper (ORM) that enables developers to work with databases using .NET objects, eliminating the need for most of the data-access code that developers typically need to write. EF Core supports various database providers, including SQL Server, SQLite, PostgreSQL, and more.

Key Features of Entity Framework Core

  • Cross-Platform: EF Core is designed to work on multiple platforms, including Windows, macOS, and Linux.
  • Code First and Database First: EF Core supports both approaches, allowing developers to define their data models in code or generate models from an existing database.
  • Migrations: EF Core provides a migration feature that helps manage changes to the database schema over time, allowing for version control of the database structure.
  • LINQ Support: EF Core allows developers to use Language Integrated Query (LINQ) to query data, making it easier to work with data in a type-safe manner.
  • Change Tracking: EF Core automatically tracks changes made to entities, simplifying the process of updating the database.

Setting Up Entity Framework Core in ASP.NET Core

To use EF Core in an ASP.NET Core application, follow these steps:

Step 1: Install Required Packages

You need to install the necessary NuGet packages for EF Core. For example, to use EF Core with SQL Server, run the following commands in your project directory:

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

Step 2: Create a Model Class

Define a model class that represents the data structure. Below is an example of a simple Product model.

        
using System.ComponentModel.DataAnnotations;

public class Product
{
public int Id { get; set; }

[Required(ErrorMessage = "Product name is required.")]
[StringLength(100, ErrorMessage = "Product name cannot exceed 100 characters.")]
public string Name { get; set; }

[Range(0.01, 10000.00, ErrorMessage = "Price must be between 0.01 and 10,000.00.")]
public decimal Price { get; set; }
}

Step 3: Create a Database Context

Create a database context class that derives from DbContext. This class will manage the entity objects during runtime and provide access to the database.

        
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}

public DbSet<Product> Products { get; set; } // DbSet for Product entity
}

Step 4: Configure the Database Connection

In the Startup class, configure the database context and specify the connection string.

        
using Microsoft.EntityFrameworkCore;

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer("YourConnectionStringHere")); // Replace with your connection string

services.AddControllers(); // Add services for controllers
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers(); // Map attribute-routed controllers
});
}
}

Step 5: Applying M igrations

After setting up the database context, you need to create and apply migrations to create the database schema. Use the following commands in the .NET CLI:

        
dotnet ef migrations add InitialCreate
dotnet ef database update

Step 6: Using the Database Context

You can now use the database context to perform CRUD operations. Below is an example of a simple controller that uses the ApplicationDbContext to manage products.

        
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly ApplicationDbContext _context;

public ProductsController(ApplicationDbContext context)
{
_context = context;
}

[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await _context.Products.ToListAsync();
}

[HttpPost]
public async Task<ActionResult<Product>> PostProduct(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetProducts), new { id = product.Id }, product);
}
}

Conclusion

Entity Framework Core is a powerful tool for data access in ASP.NET Core applications. It simplifies database interactions and allows developers to work with data in a more intuitive way. By following the steps outlined above, you can effectively set up and use EF Core in your ASP.NET Core applications, enabling you to manage your data with ease.