我已经仔细研究了这方面的答案,并且有几个问题表明这是无法做到的。
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>();
我如何映射子集合? 非常感谢。
答案 0 :(得分:2)
您应该使用期货批量查询并自己构建关系。
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>();