我已经编写了2个Linq到sql查询,但是我不喜欢我必须遍历第一个查询才能运行第二个查询。
第二个表上有一个引用第一个表Id的外键。任何人都可以改进我编写的代码或者这个解决方案是理想的吗?
using (var entities = new dbEntities())
{
var groups = (from g in entities.ObjectGroup
select g);
var mappings = (AutoMapper.Mapper.Map<IEnumerable<ObjectGroupModel>>(groups));
foreach (var map in mappings)
{
var types = (from t in entities.ObjectTypeToObjectGroupMappings
where t.ObjectGroupId == map.Id
select t.ObjectTypeId);
map.ObjectTypeIds = types;
}
return mappings;
}
感谢您的帮助。
答案 0 :(得分:0)
您可以尝试这样的事情:
var mappings = (from gr in entities.ObjectGroup
join t in entities.ObjectTypeToObjectGroupMappings
on gr.Id equals t.ObjectGroupId into subTs
from subT in subTs.DefaultIfEmpty()
group new { gr, subT } by new { gr.Id /*and other gr's properties*/} into sub
select new ObjectGroupModel
{
Id = sub.Key.Id,
/*other gr's properties via propN = sub.Key.propN*/
ObjectTypeIds = sub.Where(x => x.subT != null).Select(x => x.subT.ObjectTypeId).ToList()
}).ToList();