views:

147

answers:

0

With EF Code First CTP 4 I've created a simple project. This project consists of 2 classes, one inherited from other.

I wish to store the data in separate tables, but the default of EF 4 is to map/store these two entities in the same table.

With .ToTable(), I can change this behavior, but with this I have a side effect: when I persist a Inherited object, EF doesn't persist the common values (ex. Id) on the base class.

I'm sure I'm leaving to set some information in the mapping but do not know which.

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 });
        modelBuilder.Entity<Animal>().HasKey(p => p.Id).
                                    MapHierarchy().
                                    Case<Mammal>(a => new { a.Id, a.NumberOfLegs }).ToTable("Mammals");

        base.OnModelCreating(modelBuilder);
    }
}

public class Animal
{
    public virtual int Id { get; set; }
}

public class Mammal : Animal
{
    public int NumberOfLegs { get; set; }
}