Entity Framework One-Many TPH Mapping

泪湿孤枕 提交于 2019-12-07 11:12:03

问题


I'm using a data structure similar to this where type of animal is determined from a discriminator column in the table:

public class Farm {
    public int Id { get; set; }

    public virtual ICollection<Pig> Pigs { get; set; }

    public virtual ICollection<Cow> Cows { get; set; }
}

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

    public int FarmId? { get; set; }

    public virtual Farm Farm { get; set; }

    public string Name { get; set; }
}

public class Pig : Animal {}
public class Cow : Animal {}

Mapping:

this.Map<Pig>(m => m.Requires("Type").HasValue((int) AnimalType.Pig));
this.Map<Cow>(m => m.Requires("Type").HasValue((int) AnimalType.Cow));

But I can't seem to map the relationship between the Pigs, Cows and Farm. I've tried this from FarmMap which gives a duplicate column mapping error:

this.HasMany(t => t.Pigs)
    .WithOptional(t => t.Farm)
    .Map(m => m.MapKey("FarmId"));
this.HasMany(t => t.Cows)
    .WithOptional(t => t.Farm)
    .Map(m => m.MapKey("FarmId"));

Mapping from each of the animals doesn't work either, it generates extra columns (eg. Farm_Id and Farm_Id1 - in addition to FarmId - one for each animal type).

this.HasOptional(t => t.Farm)
    .WithMany(t => t.Pigs)
    .HasForeignKey(d => d.FarmId)

Moving the navigation property from the Animal model to the inheriting models causes a single additional column to be generated - FarmId1 (so a little closer to what I want than the above 2!)

Is there any way to achieve this?


回答1:


I'm no EF expert but from the Model-first approach I know that this would be mapped as a collection of Animal, you can then select Farm.Animals.OfType<Pig>()



来源:https://stackoverflow.com/questions/20677438/entity-framework-one-many-tph-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!