Entity Framework Filtered Navigation Properties

空扰寡人 提交于 2019-12-13 15:35:24

问题


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


回答1:


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:

http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx



来源:https://stackoverflow.com/questions/20663337/entity-framework-filtered-navigation-properties

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