entity framework一对多TPH映射
我正在使用类似于此的数据结构,其中动物的类型是从表中的鉴别器列确定的:
public class Farm { public int Id { get; set; } public virtual ICollection Pigs { get; set; } public virtual ICollection 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 {}
制图:
this.Map(m => m.Requires("Type").HasValue((int) AnimalType.Pig)); this.Map(m => m.Requires("Type").HasValue((int) AnimalType.Cow));
但我似乎无法绘制猪,牛和农场之间的关系。 我从FarmMap
尝试了这个,它给出了一个重复的列映射错误:
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"));
来自每只动物的映射也不起作用,它产生额外的列(例如, Farm_Id
和Farm_Id1
– 除了FarmId
– 每种动物类型一个)。
this.HasOptional(t => t.Farm) .WithMany(t => t.Pigs) .HasForeignKey(d => d.FarmId)
将导航属性从Animal
模型移动到inheritance模型会导致生成一个额外的列 – FarmId1
(因此比上面的2更接近我想要的!)
有没有办法实现这个目标?
我不是EF专家,但从模型优先方法我知道这将被映射为Animal的集合,然后您可以选择Farm.Animals.OfType