Code-First将一个实体映射到多张数据库表
将一个实体映射到多张数据库表,我们只能用Fluent API来做,Data Annotation无法满足要求,我们来看一下代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class People
2 {
3 public int Id { get; set; }
4 public string Name { get; set; }
5 public DateTime Birth { get; set; }
6 public bool Sex { get; set; }
7 public string Description { get; set; }
8 }
9
10 class myContext : DbContext
11 {
12 public DbSet<People> peopleSet { get; set; }
13 protected override void OnModelCreating(DbModelBuilder modelBuilder)
14 {
15 modelBuilder.Configurations.Add(new PeopleConfig());
16 }
17 }
18
19 class PeopleConfig : EntityTypeConfiguration<People>
20 {
21 public PeopleConfig()
22 {
23
24 Map(m =>
25 {
26 m.Properties(p => new { p.Sex, p.Name });
27 m.ToTable("Person");
28 });
29
30 Map(m =>
31 {
32 m.Properties(p => new {p.Description, p.Birth });
33 m.ToTable("Detail");
34 });
35 }
36 }
这里需要注意的是,在PeopleConfig中,我们先对Person表做了映射,后对Detail表做了映射,则在生成的数据库中,Person表为主表,Detail表为从表,即Detail表的主键同时也为外键,生成的数据库如下: