实体框架一对多TPH映射 [英] Entity Framework One-Many TPH Mapping
问题描述
我使用的是哪里的动物类型是从表中的鉴别列确定类似这样的数据结构:
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 {}
映射:
this.Map<Pig>(m => m.Requires("Type").HasValue((int) AnimalType.Pig));
this.Map<Cow>(m => m.Requires("Type").HasValue((int) AnimalType.Cow));
但我似乎无法映射猪,牛和农场之间的关系。我从 FarmMap
试过这赋予了重复的列映射错误:
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"));
映射也不管用,它会产生额外的列(如 Farm_Id
和 Farm_Id1
- 除了 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)
移动从动物
模式的继承车型的导航属性将导致生成一个附加列 - FarmId1
(那么一点点接近我想要比上述2!)
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?
推荐答案
我不是专家EF但是从模型第一种方法,我知道,这将被映射为动物的集合,则可以选择 Farm.Animals.OfType< ;猪>()
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>()
这篇关于实体框架一对多TPH映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!