实体框架过滤的导航属性 [英] Entity Framework Filtered Navigation Properties
问题描述
有没有办法使用EF6 /代码首先设置导航属性的过滤器?我想要实现类似于下面的内容,其中Farm.Pigs返回类型等于pig的动物的集合(但不将数据库首先从数据库中加载,而不是将它们存储在单独的表中)。这是可能吗?
public class Farm {
public int Id {get;组; }
public virtual ICollection< Animal>猪{get;组; }
public virtual ICollection< Animal>奶牛{get;组; }
}
public class Animal {
public int Id {get;组; }
public int FarmId? {get;组; }
public virtual Farm Farm {get;组; }
public string Name {get;组; }
}
public enum AnimalType {
Pig,Cow
}
更新
将更新移动到一个新问题:实体框架一个多TPH映射
你不能按照您的要求执行此操作,它是实体框架的当前限制。
如果创建了继承关系,您可以以不同的方式实现,例如
public class Animal {
public int Id {get;组; }
public AnimalType Type {get;组; }
public string Name {get;组; }
}
public class Pig:Animal {...}
public class Cow:Animal {...}
然后,您可以按照以下文章配置Table per Hierarchy(TPH):
Is there a way to set a filter on a navigation property using EF6/code first?
I want to achieve something similar to the below, where Farm.Pigs returns a collection of animals whose type is equal to pig (but without loading the whole collection from the database first - and not storing them in a separate table). Is this possible?
public class Farm {
public int Id { get; set; }
public virtual ICollection<Animal> Pigs { get; set; }
public virtual ICollection<Animal> 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 enum AnimalType {
Pig, Cow
}
Update
Moved the update to a new question: Entity Framework One-Many TPH Mapping
You can't do this in the way you asked, it is a current limitation of entity framework.
You could achieve it a different way if you created an inheritance relationship, i.e.
public class Animal {
public int Id { get; set; }
public AnimalType Type { get; set; }
public string Name { get; set; }
}
public class Pig : Animal { ... }
public class Cow : Animal { ... }
You could then configure Table per Hierarchy (TPH) as in the following article:
这篇关于实体框架过滤的导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!