我是NHibernate的新手并且在Linq上并不擅长,但是这严重地踢了我的屁股,我找不到任何关于SO的明确例子。
我需要从数据库中获取线程信息,但我需要包含一个子查询,该子查询可以计算特定线程上的帖子数。
这是一个SQL语句
Select ID, ThreadName,
(Select Count(Posts.ID) From Posts Where ThreadID = Threads.ID) as Replies
From Threads
和班级结构:
Class Thread
Property ID as Integer
Property ThreadName as String
Property Replies as Integer
End Class
Class Post
Property ID as Integer
Property ThreadID as Integer
Property PostText as String
End Class
非常感谢任何帮助。还有奖励点可以提供LINQ示例和使用NHibernate语法的示例。
答案 0 :(得分:1)
所以查询将是这样的:
C#
var query =
from thrs in session.Query<YourNamespace.Thread>() // in C# Thread would need
select new YourNamespace.Thread // precise NS to distinguish System.Threading
{
ID = thrs.ID,
ThreadName = thrs.ThreadName,
Replies = thrs.Posts.Count()
};
var list = query.ToList(); // the above statement was executed
VB:
Dim query = From t As Thread In session.Query(Of Thread)()
Select New Thread With {
.ID = t.ID,
.ThreadName= t.ThreadName,
.Replies = t.Posts.Count
}
Dim list as List(of Thread) = query.ToList()
这里非常重要的想法是,Thread
必须映射到 Posts
C#
public class Thread
{
...
// really sorry for C# ... I will learn VB syntax ...
public virtual IList<Post> Posts { get; set; }
VB
Public Class Thread
Public Overridable Property Posts As IList(Of Post)
如果这个collection of Posts
将在NHibernate中映射,那么上面的LINQ语法将开箱即用