What is Entity Framework?
Entity Framework Core is a lightweight, open-source, cross-platform object-relational mapper for .NET. It acts as a broker between your .NET application and the database server, facilitating the mapping of .NET objects to database tables and translating C# data access code into SQL statements.
Using Entity Framework Core offers several advantages:
- No need to learn a new language; utilize C# and LINQ.
- Tooling to maintain synchronization between C# models and database tables.
- Real-time tracking of changes to C# entities for effective persistence.
- Support for multiple database providers.
Now, let’s delve into the process of adding database support to an ASP.NET Core API using Entity Framework Core.
Step 1: Define Your Entity
An entity represents the data to be mapped to a database table. For instance, in a Superheroes application, you might have a SuperHero entity.
public class SuperHero
{
public int Id { get; set; }
public string Name { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Place { get; set; }
}
Step 2: Integrate DbContext
A DbContext instance manages interactions with the database and facilitates querying and saving of entity instances. It combines the Unit of Work and Repository patterns. Begin by adding the appropriate NuGet package for your database provider.
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
Then create the DbContext class and register it with the service container in Program.cs.
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
public DbSet<SuperHero> SuperHeroes { get; set; }
}
var connectionString = "Data Source=SuperHero.db";
builder.Services.AddSqlite<DataContext>(connectionString);
Step 3: Generate Database
To translate entities into database tables, you’ll need to create and apply a migration.
Obtain the dotnet-ef tool:
dotnet tool install --global dotnet-ef
Add the required NuGet package:
dotnet add package Microsoft.EntityFrameworkCore.Design
Create the migration and apply it to generate your database:
dotnet ef migrations add InitialCreate // create the migration
dotnet ef database update // apply the migration
Step 4: Create Database Records
Inject your DbContext instance into controller to create and save entity instances into database tables. The SuperHeroes.Add() method instructs Entity Framework Core to track the new game instance, while SaveChangesAsync() executes SQL statements to persist changes to the database.
[Route("api/[controller]")]
[ApiController]
public class SuperHeroController : ControllerBase
{
private readonly DataContext _context;
public SuperHeroController(DataContext context)
{
_context = context;
}
[HttpPost]
public async Task<ActionResult<List<SuperHero>>> AddHero(SuperHero hero)
{
_context.SuperHeroes.Add(hero);
await _context.SaveChangesAsync();
return Ok(await _context.SuperHeroes.ToListAsync());
}
}
Step 5: Query Database Records
Set up an endpoint to retrieve games created in the previous step. Use SuperHeroes.FindAsync() to search for the requested superhero in the DbSet. If not found, Entity Framework Core sends the corresponding SQL query to the database for retrieval.
[HttpGet("{id}")]
public async Task<ActionResult<SuperHero>> Get(int id)
{
var hero = await _context.SuperHeroes.FindAsync(id);
if (hero == null)
return BadRequest("Hero not found.");
return Ok(hero);
}
With these steps, we’ve built a fully functional database backed ASP.NET Core API using Entity Framework Core. I hope you found this guide helpful.
To explore more on this topic, you can check out the following resources:
Learn More
Register Now Registration link: