从孩子那里获得财产

时间:2014-08-13 16:26:20

标签: c# .net nhibernate orm queryover

我有以下实体:

public class Parent
{
     int Id { get; set; }
     string ParentName { get; set; }
     List<Child> Children { get; set; }
}

public class Child
{
     int Id { get; set; }
     string ChildName { get; set; }
}

以及以下dto:

public class ParentDTO
{
     int Id { get; set; }
     List<string> ChildrenNames { get; set; }
}

使用下面的QueryOver代码我可以获得父值

 ParentDTO result = null;
 Parent parentAlias = null;
 Child childAlias = null;

 var query = session.QueryOver(() => parentAlias)              
            .JoinAlias(() => parentAlias.Children, () => childAlias, JoinType.LeftOuterJoin)                           
            .SelectList(list => list.Select(c => c.Id).WithAlias(() => result.Id)
                                    .Select(c => c.ParentName).WithAlias(() => result.Name)
//this part does not work
 .Select(c => c.Children .Select(v => v.ChildName)).WithAlias(() => result.ChildrenNames) 
//                              
)
.TransformUsing(Transformers.AliasToBean<ParentDTO>());

return query.List<ParentDTO>();  

但是我似乎无法将childName值列表投射到我的ChildrenNames集合中。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

有些人在评论中说,你需要做两个查询。使用linq,你可以尝试这样的事情:

// get the parent Ids
var parentIds = session.Query<Parent>().Select(c => c.Id).ToList(); 

// get the childNames
var childNames = session.Query<Child>()
                        .Where(x => parentIds.Contains(x.ParentId)) // get on the child from parents query
                        .Select(x => new {x.Name, x.ParentId}) // get only the properties you need
                        .ToList(); // list of anon objects

// loop in memory between parentIds filling the corresponding childNames
var result = parentIds.Select(parentId => new ParentDTO() 
             { 
                Id = parentId,
                ChildrenNames = childNames.Where(x => x.ParentId == parentId).ToList()
             }).ToList();

我不确定它是否有效,但你可以在一个查询中尝试这个:

var query = from p in session.Query<Parent>()
            let names = p.Children.Select(c => c.ChildName).ToList()
            select new ParentDTO()
            {
               Id = o.Id,
               ChildrenNames = names
            };

return query.Tolist();

Obs:我没有测试它。