2

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

Community
  • 1
  • 1
Jamie
  • 4,670
  • 5
  • 35
  • 49
  • You could do this with interitance, Pig and Cows are animals... – Maess Dec 18 '13 at 16:28
  • You should get rid of the AnimalType column. EF materialises the correct type based on a "discriminator" column. Then try getting rid of your fluent mapping altogether. I'm pretty sure your model follows conventions and EF is working it out for you. There's probably a mistake in your fluent mapping that is creating extra columns but why worry about that when conventions do it for you? – Colin Dec 18 '13 at 22:14
  • Ahh sorry, I have actually removed that I just forgot to remove it from the example - unfortunately that's not the problem. – Jamie Dec 19 '13 at 07:47

1 Answers1

2

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

Matt Whetton
  • 6,616
  • 5
  • 36
  • 57
  • I had no idea entity framework could do that, thanks! – Jamie Dec 18 '13 at 16:36
  • My example probably isn't the best for this one, as I'm sure a pig isn't likely to morph into a cow however... Is it possible to change or map the discriminator column in the base type (ie. `Animal`) without a raw SQL query? – Jamie Dec 18 '13 at 17:09
  • Just to confirm you want to be able to change a pig to a cow? I'm not sure but I dont think you can do this using EF with TPH – Matt Whetton Dec 18 '13 at 17:19
  • No, however `Animal` is an existing table, so the discriminator column will be null! – Jamie Dec 18 '13 at 17:30