将一个实体映射到多张数据库表
http://www.cnblogs.com/Allen-Li/archive/2012/04/05/2433309.html
将一个实体映射到多张数据库表,我们只能用Fluent API来做,Data Annotation无法满足要求,我们来看一下代码
View Code
View Code class People { public int Id { get; set; } public string Name { get; set; } public DateTime Birth { get; set; } public bool Sex { get; set; } public string Description { get; set; } } class myContext : DbContext { public DbSet<People> peopleSet { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new PeopleConfig()); } } class PeopleConfig : EntityTypeConfiguration<People> { public PeopleConfig() { Map(m => { m.Properties(p => new { p.Sex, p.Name }); m.ToTable("Person"); }); Map(m => { m.Properties(p => new {p.Description, p.Birth }); m.ToTable("Detail"); }); } }
这里需要注意的是,在PeopleConfig中,我们先对Person表做了映射,后对Detail表做了映射,则在生成的数据库中,Person表为主表,Detail表为从表,即Detail表的主键同时也为外键,生成的数据库如下:
Fighting like Allen Iverson! Never never give up!