Reputation: 18909
I am trying to project a collection of an entity into a DTO. Easy enough with simple properties, but having an issue with collections:
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;}
}
Query goes a little something like:
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>();
EDIT UPDATE
I cannot seem to get a simple projection to run even without the transform and get: "Index was outside the bounds of the array":
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>();
Upvotes: 3
Views: 10255
Reputation: 15579
I am guessing this is what you should do..
Update your DTO to:
public class MyDTO
{
public string BlogName {get;set;}
public IList<Comments> Comments {get;set;}
}
Your modified query:
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>()
if that doesnt work then
_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())};
Upvotes: 6