[英]Nhibernate Queryover, how to access nested proeprty
this is my model 这是我的模特
public class A{
public int Id {get; set;}
public ICollection<B> bs {get; set;}
}
public class B{
public int Id {get; set;}
public ICollection<C> cs {get; set;}
}
public class C{
public int Id {get; set;}
}
now i want to get Max(Id) of C class of a B object of an A object: 现在我想获取A对象的B对象的C类的Max(Id):
public int GetMaxId(int idA, int idB)
i try some diffente way: 我尝试一些不同的方式:
var max= _session.QueryOver<A>().Select(a => a.Bs)
.Where(a => a.Id == idA).SingleOrDefault<ICollection<B>>()
.Where(b => b.Id == idB).FirstOrDefault<B>().Cs.Max(c => c.Id);
and 和
var max = _session.QueryOver<A>().Where(a => a.Id == idA).Select(a => a.Bs.Where(b => b.Id == idB)).Future<B>().Max(c => c.Id);
but nothing works 但没有任何效果
any way to do this? 有什么办法吗? Thanks 谢谢
First of all be aware that SingleOrDefault
and FirstOrDefault
end your query. 首先,请注意SingleOrDefault
和FirstOrDefault
结束您的查询。 All that comes after will be processed in memory, not on the database! 之后的所有内容都将在内存中处理,而不是在数据库中处理! Besides that, you have a chance of a NullReferenceException
after these methods. 除此之外,在这些方法之后,您还有机会出现NullReferenceException
。
To use nested properties in the QueryOver
API you need to use aliases. 要在QueryOver
API中使用嵌套属性,您需要使用别名。 As shown here under heading 'Aliases'. 如图所示这里标题“别名”下。
But the simplest way in my opinion is to use LINQ instead: 但是我认为最简单的方法是改为使用LINQ:
_session.Query<A>()
.Where(a => a.Id == idA)
.SelectMany(a => a.Bs)
.Where(b => b.Id == idB)
.SelectMany(b => b.Cs)
.Max(c => (int?)c.Id) // the cast makes sure you don't get a null reference (tnx to gt.guybrush)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.