【问题标题】:Getting properties from a child从孩子那里获取属性
【发布时间】:2014-08-13 16:26:19
【问题描述】:

我有以下实体:

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

有什么想法吗?

【问题讨论】:

  • 不支持。投影可以参考定义为many-to-one ...但不是one-to-many (没有一些非常智能的自定义转换器),请查看此以了解有关问题的更多详细信息>:stackoverflow.com/questions/24517403,这是一些解决方法:stackoverflow.com/questions/17279307
  • 最简单的就是在这里写两个查询:一个是获取父母,另一个是为每个父母获取孩子

标签: c# .net nhibernate orm queryover


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-09-26
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 2015-07-18
    • 2018-10-04
    • 1970-01-01
    相关资源
    最近更新 更多