What is Entity Framework Core
Entity Framework Core is an ORM (i.e an Object-Relational Mapper). It's a complete rewrite from the ground up. If you have any experience with previous versions of Entity Framework, you will find lot of familiar features.
EF core is lightweight, extensible, and open source software. Like .NET Core, EF Core is also cross platform. It works on windows, Mac OS, and Linux. EF core is Microsoft’s official data access platform.
Entity Framework Core DbContext class
One of the very important classes in Entity Framework Core is the DbContext class. This is the class that we use in our application code to interact with the underlying database. It is this class that manages the database connection and is used to retrieve and save data in the database.
To use the DbContext class in our application
- We create a class that derives from the DbContext class.
- DbContext class is in Microsoft.EntityFrameworkCore namespace.
DbContextOptions in Entity Framework Core
For the DbContext class to be able to do any useful work, it needs an instance of the DbContextOptions class.
The DbContextOptions instance carries configuration information such as the connection string, database provider to use etc.
We pass the DbContextOptions to the base DbContext class constructor using the base keyword as shown below.
Entity Framework Core DbSet
- The DbContext class includes a DbSet<TEntity> property for each entity in the model.
- At the moment in our application we have, 2 entity classes - Employee and Department.
- So in our AppDbContext class we have 2 corresponding DbSet properties.
- We will use these DbSet properties to query and save instances of Employee and Department classes.
- The LINQ queries against the DbSet properties will be translated into queries against the underlying database.
Seeding Data
Override OnModelCreating method to seed Employee and Department data.
AppDbContext class complete code
Create Models folder and include the following AppDbContext class in it.
Install required NuGet packages
Install the following 2 NuGet packages.
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
Database Connection String
Include the following database connection string in appsettings.json file of the REST API project.
ConfigureServices in API project Startup class
Read the connection string from appsettings.json file
Create and execute database migrations
Use the following 2 commands to create and execute the initial database migration
- Add-Migration InitialCreate
- Update-Database
No comments:
Post a Comment