Reputation: 67
I have a many-to-many relationship between two entities, Services
and Facilities
. I have a List<int>
with the ID's of the selected facilities and I need to retrieve the services for each facility.
I tried this
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)));
}
But all I got was this error:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'bool'
What's wrong with this code?
Upvotes: 2
Views: 1729
Reputation: 39376
But, why not start with the Falicities
:
var Dic= _context.Facilities.Where(f=>facilities.Contains(f.Id))
.ToDictionary(f=>f.Id,f.Services.ToList());
Upvotes: 2
Reputation: 8018
I would also suggest do not make the SQL requests within a loop. Better select all Services
, which contain your Facilities
, and then map them to a 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);
Upvotes: 0
Reputation: 3009
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());
}
Upvotes: 2