问题
I'm using the Repository and Unit Of Work Pattern with Entity Framework 5
I want to get all the "Agencies" with its "Cars" but only those Cars that have an id in the list sent by parameter and that belongs to the state sent by parameter.
For example
public IEnumerable<Agency> GetList(int stateId, string idCarList)
var ids = idTiposTarjetasList.Split(',');
var intIds = ids.Select(int.Parse);
Then I have
Uow.Agencies.GetAll()
and
Uow.Agencies.GetAllIncluding(a => a.Cars)
which retrieves an IQueryable< T >
Is there anyway I can retrieve in one query the Agencies containing its Cars but only those that have an id contained in the intIds list and stateId matching stateId parameter?
I've already seen this Stackoverflow question, but the retrieval of the IQueryable is getting me troubles to get it work.
If I write this var sortedList = from x in Uow.Agencies.GetAllIncluding(c => c.Cars) then the select can't be done (says arguments cannot be inferred from the query
This doesn't work:
var ids = idCars.Split(',');
var intIds = ids.Select(int.Parse);
var agencies = from agency in
Uow.Agencies.GetAllIncluding(c => c.Cars).Where(c => intIds.Contains(c.Cars.Id)).OrderBy(s => s.Id)
select agency;
if (agencies.Any())
{
return agencies;
}
How can I do it? Thanks! Guillermo.
回答1:
You can't fetch objects with partly loaded collections (at least, not in one statement). So you must create a type that contains the agent
object and the selected cars separately:
var agencies = from agency in Uow.Agencies.GetAll()
select new { Agency = agency,
Cars = agency.Cars.Where(c => intIds.Contains(c.Id))
};
来源:https://stackoverflow.com/questions/13479352/filtering-inner-collection-with-entity-framework-5-and-repository-pattern-and-un