让我们说我的模型看起来像这样。
public class OrganizationDTO
{
public int Id { get; set; }
public string Name { get; set; }
public List<StorageDTO> Storages { get; set; } = new List<StorageDTO>();
}
public class StorageDTO
{
public int Id { get; set; }
public string Name { get; set; }
public List<OrganizationDTO> Organizations { get; set; } = new List<OrganizationDTO>();
}
组织可能有多个存储空间,所以基本上我想在我的表中复制每个存储的组织。我想在下面的表格记录中显示
组织1 |存放1
组织1 |存储2
组织1 | Storage3
组织1 | Storage4
组织2 |存放1
组织2 |存储2
我尝试按存储集合对它们进行分组,但它并没有像我想要的那样复制我的记录。
var result = Context.Storages
.SelectMany(org => org.Organizations)
.GroupBy(org => org)
.Select(grouping => grouping.FirstOrDefault())
.OrderBy(org => org.Name)
.ProjectTo<SomeDTO>();
答案 0 :(得分:3)
看起来你只是想要平息关系。
var query =
from storage in Context.Storages
from org in storage.Organizations
select new {Storage = storage, Organization = org };
var result = query
.OrderBy(row => row.Organization.Name)
.ProjectTo<SomeDTO>();
答案 1 :(得分:2)
var result = Context.Organizations
.SelectMany(organizationDTO =>organizationDTO
.Storages
.Select(storage =>
new {organizationDTO, storage}));