2011-09-05 70 views
0

我有一個讓我發瘋了查詢,,當我在SQL運行它,它工作正常,但我不知道如何將其更改爲LINQ to SQL的我怎樣才能更改一個SQL查詢linq 2 nhibernate?

查詢是:

SELECT  organizationstructure.PositionTitle.Title, organizationstructure.Person.FirstName, organizationstructure.Person.LastName, 
        organizationstructure.Department.Name 
FROM   organizationstructure.Department INNER JOIN 
        organizationstructure.Accountability AS Accountability_1 ON organizationstructure.Department.PartyId = Accountability_1.ParentPartyId INNER JOIN 
        organizationstructure.Accountability INNER JOIN 
        organizationstructure.Person ON organizationstructure.Accountability.ChildPartyId = organizationstructure.Person.PartyId INNER JOIN 
        organizationstructure.Position ON organizationstructure.Accountability.ParentPartyId = organizationstructure.Position.PartyId ON 
        Accountability_1.ChildPartyId = organizationstructure.Position.PartyId INNER JOIN 
        organizationstructure.PositionTitle ON organizationstructure.Position.PositionTitleId = organizationstructure.PositionTitle.PositionTitleId 

和我認爲這是錯誤的,但我把它改爲:

query// query is iqueryable of position 
      .Join(Repository<Accountability>.Find(), p => p.Id, a => a.Child.Id, 
        (p, a) => new Tuple<string, string, int?>(((Department)a.Parent).Name, p.PositionTitle.Title, p.Id)) 

      .Join(Repository<Accountability>.Find(), p => p.Item3, p => p.Parent.Id, 
        (p, d) => new Tuple<string, string, int?, string>(p.Item1, p.Item2, p.Item3, d.Child == null ? string.Empty : string.Format("{0}", ((Person)d.Child).FirstName) + " " + ((Person)d.Child).LastName)) 

什麼是錯的或它可以改變這個查詢?

回答

0

通常不得不在你的linq中向nhibernate做過多的顯式連接,這表示你沒有適當地將你的數據庫映射到你的域。如果沒有對象之間的映射,那麼你只需要在你的linq中複製SQL,這有點浪費時間。

您的映射應該指定域中對象之間的關係 - 例如,「Person」可能會引用「PositionTitle」。如果您使用映射來以這種方式建立關係,那麼您的查詢可能會看起來像這樣:

var results = 
    from 
     p in mySession.Query<Person> 
    select 
     new PersonalDetails 
     { 
      Title = p.PositionTitle.Title, 
      FirstName = p.FirstName, 
      LastName = p.LastName 
      DepartmentName = p.Party.Department.Name 
     }; 
相關問題