LINQ查询列表中的实体列表

时间:2016-03-17 16:58:49

标签: c# entity-framework linq

我在两个实体ServicesFacilities之间存在多对多关系。我有List<int>个所选设施的ID,我需要检索每个设施的服务。

我试过这个

 Dictionary<int, List<Service>> Dic = new Dictionary<int, List<Service>>();

        foreach (var id in facilities)
        {
            Dic.Add(id,  _context.Services.Where(x => x.Facilities.Where(y => y.Id == id)));
        }

但我得到的只是这个错误:

  

无法隐式转换类型   &#39; System.Collections.Generic.IEnumerable&#39;   到了布尔&#39;

此代码有什么问题?

3 个答案:

答案 0 :(得分:2)

 Dictionary<int, List<Service>> Dic = new Dictionary<int, List<Service>>();

    foreach (var id in facilities)
    {
        Dic.Add(id,  _context.Services.Where(x => x.Facilities.Any(y => y.Id == id)).ToList());
    }

答案 1 :(得分:2)

但是,为什么不从Falicities开始:

var Dic= _context.Facilities.Where(f=>facilities.Contains(f.Id))
                            .ToDictionary(f=>f.Id,f.Services.ToList());

答案 2 :(得分:0)

我还建议不要在循环中发出SQL请求。最好选择包含Services的所有Facilities,然后将其映射到Dictionary<id,List<Service>

 var services = _ctx
    .Services 
    .Where(x => x.Facilities.Select(y => y.Id).Intersect(facilities).Any())
    .ToList();

facilities
    .Select(id => new { 
        Id = id, 
        Services = services.Where(service => service.Facilities.Any(y => y.Id == id)).ToList()
    })
    .ToDictionary(x => x.Id, x => x.Services);