I have an entity Framework model with the following:
class Farm{
string owner;
List<Animal> animals;
DateTime StartDate;
}
class Animal{
string Name;
DateTime DOB;
}
Problem:
I would like to select a collection of farms whose start date is >= 2013/01/01 along with it's animals, but also filtered by DOB >= 2013/06/01.
I've tried the following:
Try1:
//This still shows all animals from each farm, if there is at least one
//animal with the required DOB
var x = context.Farm.Where(y => y.StartDate >= myDate
&& y.Animal.Any(z => z.DOB >= otherDate)
).Include("Animal");
Try2:
//I subclassed the Farm class because i cant instantiate the class
//from Entity Framework directly, and that should be my return type.
class Temp:Farm{}
var x = context.Farm.Where(y => y.StartDate >= myDate).Include("Animal")
.Select(z => new Temp(){
owner = z.owner,
animals = new TrackableCollection<Animal>(){ z.animals.Where(y => y.DOB >= newDate).SingleOrDefault() });
//Couple of things here:
//1: I instantiated a new TrackableCollection because thats what the collection
//type of Animal is inside Entity Framework.
//2: This still doesnt work for some reason, if i use this approach, the list
//of animals in the farm comes with 0 elements.
Try3:
After reading this: Ef-query-with-conditional-include
var x = (from farm in ctx.Farm
from animal in farm.Animal
where animal.DOB => newDate
select new{farm, animal}).AsEnumerable().Select(x=> x.farm).Distinct().ToList();
//I have no idea how this works, but it does...
Anyone care to explain how the above works?
Basically the query is selecting the parent entity and the child entity filtered by the required parameters, and entity framework through "Relationship Fixup" knows that the selected children are associated with the selected parents, so they get added to the parent collection as well. I see it kind of a hacky solution, but it works indeed.
--Andrei D.