Filtering inner collection with Entity Framework 5 and Repository pattern and Unit of Work

青春壹個敷衍的年華 提交于 2019-12-08 13:35:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!