如何将sql查询更改为linq 2 nhibernate?

时间:2011-09-05 04:22:59

标签: sql-server-2005 linq-to-nhibernate

我有一个让我疯狂的查询,当我在sql中运行它工作正常但我不知道如何将其更改为linq to sql

查询是:

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))

它有什么问题或者我可以改变这个查询吗?

1 个答案:

答案 0 :(得分: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
        };