好吧,首先,我的簡單領域模型是2個具有一對多關係的類,一個簡單的父 - >子關係。 A「分享Tweet」有一個或多個「投票」,但每張票屬於只有一個鳴叫等NHibernate - 如何編寫此查詢:選擇父母併爲每個匹配條件的父母找到子女
public class Tweet
{
public virtual long Id { get; set; }
public virtual string Username { get; set; }
public virtual string Message { get; set; }
public virtual ISet<Vote> Votes { get; set; }
}
public class Vote
{
public virtual long Id { get; set; }
public virtual long TwitterUserId { get; set; }
public virtual DateTime VotedDate { get; set; }
public virtual Tweet Tweet { get; set; }
}
我試着寫在任何HQL,或的ICriteria NHibernate的LINQ查詢,選擇所有推文,但也補充說,選擇兩列:
- 投票數的計數,並...
- 無論特定的用戶投票爲鳴叫,基於特定TwitterUserId
有了兩個額外的列,我不希望收到Tweet域對象,並且可能需要運行報告查詢,那沒問題。但我正在努力弄清楚如何編寫這個查詢。
我知道如何將它寫成存儲過程或使用LINQ 2 SQL。如果有幫助,我會將其表示爲LINQ to SQL查詢。
long userId = 123;
var tweets = from t in dataContext.Tweets
where t.Application == app
orderby t.PostedDate desc
select new TweetReport()
{
Id = t.Id,
Username = t.Username,
Message = t.Message,
TotalVotes = t.Votes.Count(),
HasVoted = t.Votes.Any(v => v.TwitterUserId == userId)
};
我知道這將在LINQ 2 SQL工作,併產生相當有效的T-SQL,但我無法弄清楚如何在NHibernate的寫。
更新:我試圖通過使用NHibernate LINQ provider built for NHibernate v2,如運行在NHibernate的上述LINQ查詢:
var tweets = from t in Session.Linq<Tweet>()
where (snip)
但沒有奏效。 Nhibernate 3.0中的LINQ支持有所改進嗎?我有點不情願使用3.0版本,因爲它仍然是alpha版本,但是如果這樣會起作用,那麼我可能會放棄它。
更新2:感謝迭戈Mijelshon的建議下,我升級到NHibernate的3.0阿爾法2並寫在LINQ查詢:
var tweets = from t in Session.Query<Tweet>()
where t.App == app
orderby t.PostedDate descending
select t;
int totalRecords = tweets.Count();
var pagedTweets = (from t in tweets
select new TweetReport()
{
Id = t.Id,
TwitterId = t.TweetId,
Username = t.Username,
ProfileImageUrl = t.ImageUrl,
Message = t.Message,
DatePosted = t.PostedDate,
DeviceName = t.Device.Name,
DeviceUrl = t.Device.Url,
TotalVotes = t.Votes.Count(),
HasVoted = t.Votes.Any(v => v.TwitterUserId == userId)
})
.Skip(startIndex)
.Take(recordsPerPage)
.ToList();
return new PagedList<TweetReport>(pagedTweets,
recordsPerPage, pageNumber, totalRecords);
我試着用舊的NHibernate LINQ提供程序(與NHibernate v2一起工作)提供,並且它不工作,拋出異常。我做了一些研究,NHibernate的LINQ提供者有一些限制,不支持諸如子選擇之類的東西。我把它LINQ到NHibernate V3是大幅改善? – 2010-09-15 15:51:39
是的,新的集成提供商支持更多的場景。我專門測試了上面的查詢,並且工作正常。 – 2010-09-15 16:45:21
真棒,它工作出色,謝謝! – 2010-09-16 01:41:15