您的位置:首页 > 数据库

将一个实体映射到多张数据库表

2012-04-21 22:30 267 查看
/article/5291744.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表的主键同时也为外键,生成的数据库如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: