我仔细寻找了这方面的答案,有几个问题表明这是不可能的。
Nhibernate projection with child collection
NHibernate QueryOver projections - projecting collections to DTO
NHibernate Projections - how to project collections
所以我想知道将子集合投影到我的 DTO 的一个好的解决办法。 我需要运行两个单独的投影并手动将子项添加到父项吗?
我正在使用 NH 3.3.1 我有以下 DTO 数据结构
public class ProviderDto
{
public int Id { get; set; }
public string Name { get; set; }
public IList<EmployerDTO> Employers { get; set; }
}
public class EmployerDTO
{
public int Id { get; set; }
public string Name { get; set; }
}
我想通过投影将我的提供商和雇主域实体映射到此结构。 (在这个简单的场景中,我的域实体与我的 dto 非常相似)
Employer employerAlias = null;
Provider providerAlias = null;
ProviderDto providerDto = null;
var dto = session.QueryOver<Provider>(() => providerAlias)
.JoinAlias(x => x.Employers, () => employerAlias)
.Where(()=> providerAlias.Id == 1)
.Select(Projections.ProjectionList()
.Add(Projections.Property(() => providerAlias.Id).WithAlias(() => providerDto.Id))
.Add(Projections.Property(() => providerAlias.Name).WithAlias(() => providerDto.Name))
//This is where I cannot project my child employer collection
.TransformUsing(Transformers.AliasToBean<ProviderDto>()).List<ProviderDto>();
如何映射子集合? 非常感谢。
最佳答案
您应该使用 future 批量查询并自行构建关系。
Employer employerAlias = null;
Provider providerAlias = null;
ProviderDto providerDto = null;
EmployerDto employerDto = null;
var providers = session.QueryOver<Provider>(() => providerAlias)
.JoinAlias(x => x.Employers, () => employerAlias)
.Where(()=> providerAlias.Id == 1)
.Select(Projections.ProjectionList()
.Add(Projections.Property(() => providerAlias.Id).WithAlias(() => providerDto.Id))
.Add(Projections.Property(() => providerAlias.Name).WithAlias(() => providerDto.Name))
.TransformUsing(Transformers.AliasToBean<ProviderDto>()).Future<ProviderDto>();
var employers = session.QueryOver<Employer>(() => employerAlias)
//Etc
.TransformUsing(Transformers.AliasToBean<EmployerDto>()).Future<EmployerDto>();
然后就是将正确的雇主映射到提供商的问题。为此,您可能需要 DTO 中的更多信息,但使用 Future 查询,您只需进行一次数据库往返即可获取所有信息。
编辑:
为了让哪些雇主映射到哪些提供商。
session.QueryOver(() => provider)
.JoinAlias(() => provider.Employers, () => employer)
.SelectList(list => list.Select(() => provider.Id).WithAlias(() => peDTO.ProviderId)
.Select(() => employer.Id).WithAlias(() => peDTO.EmployerId))
.TransformUsing(Transformers.AliasToBean<ProviderEmployerMapDTO>()).Future<ProviderEmployerMapDTO>();
关于NHibernate 子集合投影到 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17279307/