In Code-First approach you create the entity classes only. Then with migration commands the EF Core creates the database based on these entity classes.
To understand how the Code-First approach works. First create a new ASP.NET Core project and Install Entity Framework Core on it.
In this project I will be dealing with a Company application that contains information about its employees, departments, etc.
Create a class Information.cs inside the Models folder. It will contain information about the company like company id, name, license, year of establishment and yearly revenue.
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; } }
Next create a Context class and name it CompanyContext.cs. Place it inside the Models folder.
public class CompanyContext : DbContext { public DbSet<Information> Information { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer(@"Server=vaio;Database=Company;Trusted_Connection=True;"); } } }
With Migration you can create the database based on the Entity & Context classes. Inside the OnConfiguring() method, I have provided the connection string for the database. Here in this case the database name is company.
In Visual Studio, open NuGet Package Manager Console from Tools > NuGet Package Manager >Package Manager Console and enter the following command:
PM> add-migration CompanyDB
Or, you can do the same thing with dotnet CLI by executing the following command:
PM> dotnet ef migrations add CompanyDB
The command will create Migrations folder on your project.
Now create the database by executing the update-database command on the Package Manager Console:
PM> update-database –verbose
Or, you can run the dotnet CLI command to do the same thing:
PM> dotnet ef database update
The command will execute and will create the Company database which you can open and see on your SQL Server.
Now that my database is ready, let me insert a record on the Information table.
Add the following code on a Index Action of your Controller.
using (var context = new CompanyContext()) { var info = new Information() { Name="YogiHosting", License="XXYY", Revenue=1000, Establshied=Convert.ToDateTime("2014/06/24") }; context.Information.Add(info); context.SaveChanges(); }
Once the Action is called, the code will execute, and a new record is added to the Information table.
You can see the new record on the SQL Server.
Share this article -