1.将多个实体类映射到数据库中的一个表
要将多个实体映射到一个数据库表需要满足:
a. 两个实体必须是一对一关系
b.两个实体共享一个主键
1 public class MyContext:DbContext 2 { 3 public MyContext() 4 : base("test") 5 { } 6 protected override void OnModelCreating(DbModelBuilder modelBuilder) 7 { 8 modelBuilder.Entity<Person>() 9 .HasRequired(p => p.Detail) 10 .WithRequiredPrincipal(); 11 } 12 public DbSet<Person> Persons { get; set; } 13 public DbSet<PersonDetail> PersonDetails { get; set; } 14 15 } 16 17 [Table("Person")] 18 public class Person 19 { 20 public int Id { get; set; } 21 public string Name { get; set; } 22 public bool Sex { get; set; } 23 public PersonDetail Detail { get; set; } 24 } 25 [Table("Person")] 26 public class PersonDetail 27 { 28 [Key,ForeignKey("Person")] 29 public int Id { get; set; } 30 public DateTime Birth { get; set; } 31 public byte[] Photo { get; set; } 32 public Person Person { get; set; } 33 } 34 }
2.将实体类型的 CLR 属性映射到数据库中的多个表
1 public class MyContext:DbContext 2 { 3 public MyContext() 4 : base("test") 5 { } 6 protected override void OnModelCreating(DbModelBuilder modelBuilder) 7 { 8 modelBuilder.Entity<Person>() 9 .Map(p => 10 { 11 p.Properties(t => new { t.Id, t.Name, t.Sex }); 12 p.ToTable("Person"); 13 }) 14 .Map(p => 15 { 16 p.Properties(t => new { t.Birth, t.Photo }); 17 p.ToTable("PersonDetails2"); 18 } 19 ); 20 } 21 public DbSet<Person> Persons { get; set; } 22 } 23 24 [Table("Person")] 25 public class Person 26 { 27 public int Id { get; set; } 28 public string Name { get; set; } 29 public bool Sex { get; set; } 30 public DateTime Birth { get; set; } 31 public byte[] Photo { get; set; } 32 }