Model is a collection of classes to interact with the database. We will create a simple class called Student
and add the following code.
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public DateTime BirthDate { get; set; }
public int Salary { get; set; }
}
The database context class provides the main functionality to coordinate Entity Framework with a given data model.
Microsoft.EntityFrameworkCore.DbContext
class.So let's add a new class EmployeeContext
, and replace the following code.
public class EmployeeContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Data Source=(localdb)\ProjectsV13;Initial Catalog=EmployeeContextDb;");
}
public DbSet<Employee> Employees { get; set; }
}
This code creates a DbSet
property for each entity set. In Entity Framework terminology, an entity set typically corresponds to a database table, and an entity corresponds to a row in the table.
The Entity Framework will create an empty database for you. So we need to write a method that's called after the database is created to populate it with test data.
public static void Initialize()
{
using (EmployeeContext context = new EmployeeContext())
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var employees = new List<Employee>
{
new Employee { Name="Carson Alexander", BirthDate = DateTime.Now.AddYears(-24), Salary = 10000 },
new Employee { Name="Meredith Alonso", BirthDate = DateTime.Now.AddYears(-41), Salary = 30000 },
new Employee { Name="Arturo Anand", BirthDate = DateTime.Now.AddYears(-63), Salary = 43000 },
new Employee { Name="Gytis Barzdukas", BirthDate = DateTime.Now.AddYears(-58), Salary = 40500 },
new Employee { Name="Yan Li", BirthDate = DateTime.Now.AddYears(-49), Salary = 32000 },
};
employees.ForEach(a => context.Employees.Add(a));
context.SaveChanges();
}
}
In the Main
method, replace the following code.
static void Main(string[] args)
{
Initialize();
using (EmployeeContext context = new EmployeeContext())
{
int employees = context.Employees.Count();
Console.WriteLine("Total Employees: {0}", employees);
}
}
Now when you run your application for the first time, the database will be created, and seeded with test data and you will see the following output.
Total Employees: 5