這裏的問題包括將用LINQ寫成的語句翻譯成SQL語法成NHibernate的等價物。在LINQ to SQL中的代碼看起來像這樣:使用NHibernate的HQL進行多個內部連接的查詢
var whatevervar = from threads in context.THREADs
join threadposts in context.THREADPOSTs
on threads.thread_id equals threadposts.thread_id
join posts1 in context.POSTs
on threadposts.post_id equals posts1.post_id
join users in context.USERs
on posts1.user_id equals users.user_id
orderby posts1.post_time
where threads.thread_id == int.Parse(id)
select new
{
threads.thread_topic,
posts1.post_time,
users.user_display_name,
users.user_signature,
users.user_avatar,
posts1.post_body,
posts1.post_topic
};
它本質上是試圖抓住給定的論壇主題內的職位名單。我已經能夠想出(與本網站的用戶有幫助的幫助下)爲NHibernate的最好的是:
var whatevervar = session.CreateQuery("select t.Thread_topic, p.Post_time, " +
"u.User_display_name, u.User_signature, " +
"u.User_avatar, p.Post_body, p.Post_topic " +
"from THREADPOST tp " +
"inner join tp.Thread_ as t " +
"inner join tp.Post_ as p " +
"inner join p.User_ as u " +
"where tp.Thread_ = :what")
.SetParameter<THREAD>("what", threadid)
.SetResultTransformer(Transformers.AliasToBean(typeof(MyDTO)))
.List<MyDTO>();
但是,這並不解析很好,抱怨別名連接表是空引用。 MyDTO是輸出的自定義類型:
public class MyDTO
{
public string thread_topic { get; set; }
public DateTime post_time { get; set; }
public string user_display_name { get; set; }
public string user_signature { get; set; }
public string user_avatar { get; set; }
public string post_topic { get; set; }
public string post_body { get; set; }
}
我出出主意,並同時通過直接的SQL查詢這樣做是可行的,我希望做正確,沒有擊敗使用的目的ORM。
在此先感謝!
編輯:
數據庫看起來是這樣的:http://i41.tinypic.com/5agciu.jpg(還不能發表圖片。)
奇怪的名字是由NConstruct Lite生成的XML的結果,我用它來製作ORM文件和其他東西。主鍵從「smth_id」更改爲「Id」,外鍵從「smth_id」更改爲「Smth_」。 – 2010-04-18 10:07:30