我正在尝试将实体的集合投影到DTO中。简单的属性很容易,但收藏有问题:
public class Blog
{
public string Name {get;set;}
public IList<Comments> Comments {get;set;}
//... more properties
}
public class Comments
{
public Blog Blog {get;set;}
//... more properties
}
public class MyDTO
{
public string BlogName {get;set;}
public IList<Comments> {get;set;}
}
查询有点像:
var dto = _session.QueryOver<Blog>(() => blogAlias)
.JoinAlias(x => x.Comments, () => commentsAlias, JoinType.LeftOuterJoin)
.Select(
Projections.Property(() => blogAlias.Reference).WithAlias(() => myDTO.Reference),
// what project here to project blogAlias.Comments into myDTO.Comments))
.TransformUsing(Transformers.AliasToBean<MyDTO>()
.SingleOrDefault<MyDTO>();
编辑更新
即使没有变换,我似乎无法进行简单的投影并得到: “索引超出了数组的范围”:
var dto = _session.QueryOver<Blog>(() => blogAlias)
.JoinAlias(x => x.Comments, () => commentsAlias, JoinType.LeftOuterJoin)
.Select(
Projections.Property(() => blogAlias.Reference).WithAlias(() => myDTO.Reference),
Projections.Property(() => blogAlias.Comments).WithAlias(() => myDTO.Comments)
.List<object>();
答案 0 :(得分:5)
我猜这是你应该做的......
将您的DTO更新为:
public class MyDTO
{
public string BlogName {get;set;}
public IList<Comments> Comments {get;set;}
}
您修改过的查询:
var dto = _session.QueryOver<Blog>(() => blogAlias)
.JoinAlias(x => x.Comments, () => commentsAlias, JoinType.LeftOuterJoin)
.Select(Projections.Property(() => blogAlias.Reference).WithAlias(() => myDTO.Reference),
Projections.Property(() => blogAlias.Comments).WithAlias(() => myDTO.Comments),
.TransformUsing(Transformers.AliasToBean<MyDTO>()
.SingleOrDefault<MyDTO>()
如果那不起作用,那么
_session.QueryOver<Blog>(() => blogAlias)
.JoinAlias(x => x.Comments, () => commentsAlias, JoinType.LeftOuterJoin)
.Select(Projections.Property(() => blogAlias.Reference),
Projections.Property(() => blogAlias.Comments))
.SingleOrDefault<object[]>()
.Select(x=>new MyDTO {BlogName=(string)x[0],Comments=x[1].Select(y=>y.ToString()).ToList())};