2011-09-05 68 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 
     }; 
相关问题