use*_*116 6 c# linq parent-child sql-server-2008 linq-to-sql
我有以下三个Linq To Sql实体:Location,Institution和Building。
位置表只是一个LocationId和LocationTypeId。
机构和建筑物都从位置表中以一对一关系获取其ID,而机构表与建筑物表具有一对多关系。
我正在尝试返回机构及其所有子代的所有位置记录。以下查询返回我所需要的内容,但它缺少父机构位置记录。
var query = dc.Locations.SelectMany(l => l.Institutions, (loc, inst) => new { loc, inst })
.SelectMany(i => i.inst.Buildings, (locInst, bld) => bld.Location );
Run Code Online (Sandbox Code Playgroud)
我怎样才能把父母和孩子们包括在内?
更新:
如果在原始位置查询上使用联合,则可以获得我想要的记录,但是我仍然想知道这是否是最佳解决方案。这是与联盟的代码。
IQueryable<Location> locations = dc.Locations;
locations.SelectMany(l => l.Institutions, (loc, inst) => new { loc, inst })
.SelectMany(i => i.inst.Buildings, (locInst, bld) => bld.Location)
.Union(locations);
Run Code Online (Sandbox Code Playgroud)
嗯,这是一个棘手的问题,我认为它不会变得更好,尽管如果您想要某种排序,例如首先是机构位置,然后是机构建筑位置,您可以这样做:
locations.SelectMany(l => l.Institutions, (loc, inst) => new { loc, inst })
.SelectMany(i => i.inst.Buildings.Union(new List<Building> { new Building { Location = i.loc } }), (locInst, bld) => bld.Location);
Run Code Online (Sandbox Code Playgroud)
但是代码从这里并没有变得更干净,您的解决方案非常简单并且可以完成工作。
这会影响性能并消耗更多内存(如果重要的话),但是如果这是您正在寻找的,我希望它有所帮助。(因为位置的存储顺序)
| 归档时间: |
|
| 查看次数: |
2067 次 |
| 最近记录: |