Jamie
Jamie

Reputation: 4980

Entity Framework Filtered Navigation Properties

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

Upvotes: 2

Views: 913

Answers (1)

Matt Whetton
Matt Whetton

Reputation: 6786

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

Upvotes: 2

Related Questions