繁体   English   中英

从孩子那里获得财产

[英]Getting properties from a child

我有以下实体:

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代码,我可以获取Parent值

 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集合中。

有任何想法吗?

正如有些人在评论中所说,您需要执行两个查询。 使用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:我没有测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM