The Entity Framework Core Code-First approach builds the database and tables based on entity classes and DbContext configurations.
The Code-First Approach is useful when we are starting a new project and do not have a clear image of the database. When working with EF Core, this is the preferred method, and the database and tables are created when migration is executed.
If you had previously worked with Entity Framework 6, you would have used the Database-First technique and built an EDMX file. The EDMX file includes a snapshot of the database, including its tables, stored procedures, and relationships. The focus has shifted to the Code-First strategy, and Microsoft has placed a strong emphasis on it. We may safely claim that the database-first strategy is all but dead.
Create a new ASP.NET Core project and install the Entity Framework Core package to learn how the Code-First strategy works. In this assignment, we will be working with companies that have sections such as personnel, departments, and so on.
Create Entity & DbContext
Inside the Models folder, create a class named Information. cs. It will include information about the various firms such as their company id, name, license, year of incorporation, and yearly income earned.
namespace EFCoreExample.Models { public class Information { public int Id { get; set; } public string Name { get; set; } public string License { get; set; } public DateTime Establshied { get; set; } public decimal Revenue { get; set; } } }
Then, for EF Core, build a Database Context (DbContext) and call it CompanyContext.cs. Put it in the Models folder.
using Microsoft.EntityFrameworkCore; namespace EFCoreExample.Models { public class CompanyContext : DbContext { public CompanyContext(DbContextOptions<CompanyContext> options) : base(options) { } public DbSet<Information> Information { get; set; } } }
In the app’s Program.cs class, we now register the DbContext as a service. So we add the code line shown below to it.
builder.Services.AddDbContext<CompanyContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
Migrations EF Core
We may build the database and its tables based on the Entity & Database Context classes by using migrations. Verify that the database has been given in the database connection string. In this instance, the SQL Server Express LocalDB has a database with the name Company.
To create a migration, open the NuGet Package Manager Console window in Visual Studio by selecting Tools NuGet Package Manager Console, and then type the following PMC command.
PM> add-migration CompanyDB
On the project, the command will create a Migrations folder.
The update-database PMC command on the Package Manager Console is now used to create the database:
PM> update-database
The command will run and create the Company database, which can be opened and displayed in Visual Studio’s SQL Server Object Explorer window
Using the Entity Framework Core Code-First approach, we have been able to successfully create the database. The next step is to add a new record to this database.
Create a Record
Let’s use Entity Framework Core to create a new record on the Information table. On a controller, we add a new action method that will generate a record. Below is a list of the code.
public class HomeController : Controller { private CompanyContext context; public HomeController(CompanyContext cc) { context = cc; } public IActionResult CreateInformation() { var info = new Information() { Name = "The Code Hubs", License = "XXYY", Revenue = 1000000, Established = Convert.ToDateTime("2020/01/24") }; context.Entry(info).State = EntityState.Added; context.SaveChanges(); return View(); } }
The code will run after the Action is invoked, adding a new entry to the Information table.
Entity Framework Core Seed Data
Through our code, we can build the database and load it with test data. The database is being seeded at this point. Create a new static class named DbInitializer.cs in the app’s “Data” folder to do this. The seeding process is handled by the Initialize method, which also contains test records that will be added to the database.
using EFCoreExample.Models; namespace EFCoreExample.Data { public static class DbInitializer { public static void Initialize(CompanyContext context) { // Look for any students. if (context.Information.Any()) { return; // DB has been seeded } var infos = new Information[] { new Information { Name = "The Code Hubs", License = "XXYY", Revenue = 1000, Establshied = Convert.ToDateTime("2020/01/01") }, new Information{ Name ="Microsoft", License ="XXXX", Revenue = 1000, Establshied = Convert.ToDateTime("2014/07/14") }, new Information{ Name ="Google", License ="RRRRR", Revenue = 1000, Establshied = Convert.ToDateTime("2019/06/18") }, new Information{ Name ="Apple", License ="XADFD", Revenue = 1000, Establshied = Convert.ToDateTime("2022/02/02") }, new Information{ Name ="SpaceX", License ="##@$", Revenue = 1000, Establshied = Convert.ToDateTime("2030/10/01") } }; context.Information.AddRange(infos); context.SaveChanges(); } } }
Add the code below to the Program class of the app to call this class.
using (var scope = app.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService<CompanyContext>(); context.Database.EnsureCreated(); DbInitializer.Initialize(context); }
In the situation that no database is present, the EnsureCreated method builds one. The DbInitializer follows. When invoked, initialize(context) performs the seeding process.
Drop the database first, then run the programme to test it. The software looks for the database but discovers that it is empty. The database is then created, and test data is added. This method allows us to avoid using the Migration commands that we previously used to construct the database.