使用EF Code First CTP 4,我创建了一个简单的项目.该项目由2个类组成,其中一个继承自其他类.
我希望将数据存储在单独的表中,但EF 4的默认值是将这两个实体映射/存储在同一个表中.
有了.ToTable()
,我可以改变这种行为,但有了这个我有副作用:当我持久化一个Inherited对象时,EF不会在基类上保留公共值(例如Id).
我确定我要离开在映射中设置一些信息,但不知道哪个.
static void Main(string[] args)
{
Database.SetInitializer<ZooContext>(new RecreateDatabaseIfModelChanges<ZooContext>());
using (ZooContext ctx = new ZooContext())
{
Mammal mam = new Mammal() ;
mam.NumberOfLegs = 4;
ctx.Animals.Add(mam);
// ctx.Mammals.Add(mam) as the same behavior
ctx.SaveChanges();
}
}
public class ZooContext : DbContext
{
public DbSet<Animal> Animals { get; set; }
public DbSet<Mammal> Mammals { get; set; }
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
modelBuilder.Entity<Animal>().HasKey(p => p.Id).
MapHierarchy().
Case<Animal>(a => new { a.Id }); …
Run Code Online (Sandbox Code Playgroud)