Reputation: 4980
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
}
Moved the update to a new question: Entity Framework One-Many TPH Mapping
Upvotes: 2
Views: 913
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:
Upvotes: 2