Database Reference
In-Depth Information
In this simple model, we have entities that represent associates and their salary history.
To start, this example leverages the Code-First approach for Entity Framework. In Listing 3-1, we create the entity
classes.
Listing 3-1. Associate and AssociateSalary Entity Types
public class Associate
{
public Associate()
{
AssociateSalaries = new HashSet<AssociateSalary>();
}
public int AssociateId { get; set; }
public string Name { get; set; }
public virtual ICollection<AssociateSalary> AssociateSalaries { get; set; }
}
public class AssociateSalary
{
public int SalaryId { get; set; }
public int AssociateId { get; set; }
public decimal Salary { get; set; }
public DateTime SalaryDate { get; set; }
public virtual Associate Associate { get; set; }
}
Next, in Listing 3-2, we create the DbContext object required for our Code-First approach. Note in the
OnModelCreating method how we explicitly map the SalaryId property as the primary key for the AssociateSalary.
When using Code First, if a property has the name Id or <table name>Id , Entity Framework assumes that it is the
primary key for the table. Otherwise, you must explicitly specify the key, as we have done here.
Listing 3-2. The DbContext Object
public class EFRecipesEntities : DbContext
{
public EFRecipesEntities()
: base("ConnectionString")
{
}
public DbSet<Associate> Associates { get; set; }
public DbSet<AssociateSalary> AssociateSalaries { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Associate>().ToTable("Chapter3.Associate");
modelBuilder.Entity<AssociateSalary>().ToTable("Chapter3.AssociateSalary");
// Explicilty assign key as primary key in AssociateSalary does not meet
// Entity Framework default mapping conventions.
 
Search WWH ::




Custom Search