将sql left join转换为linq2sql代码而不嵌套查询

时间:2013-02-11 15:29:37

标签: .net sql-server linq tsql linq-to-sql

我需要将此SQL格式化为LINQ2SQL查询。我有第二次加入的问题(左)。我不想使用嵌套查询,所以我编写了有效的SQL。提前谢谢。

select * from 
Accounts a 
inner join
Addresses ea on a.GUID = ea.UID 
left join 
Addresses ea2 on a.GUID = ea2.GUID and AddressTypeID = 2    
where 
ba.AccountID = 100 and
ea.AddressTypeID = 1

我的linq2SQL代码是:

var data =
                from account in dc.Accounts                    
                join primaryAddress in dc.Addresses on account.GUID equals
                    primaryAddress.GUID
                join secondaryAddress in dc.Addresses on account.GUID equals
                    secondaryAddress.GUID
                    into leftSecondaryAddress
                from secondaryAddress in
                    leftSecondaryAddress.Where(
                        x =>
                        x.AddressTypeID == 2).DefaultIfEmpty()                    
                where
                    brokerAccount.AccountID == 100 &&
                    primaryAddress.AddressTypeID == 1

我应该改变什么?

2 个答案:

答案 0 :(得分:0)

如果您使用anonymous type加入多列,则可以改进查询:

var data =
    from account in dc.Accounts                    
    join primaryAddress in dc.Addresses on account.GUID equals primaryAddress.GUID
    join secondaryAddress in dc.Addresses on new { account.GUID, AddressTypeID = 2 } equals new { secondaryAddress.GUID, secondaryAddress.AddressTypeID }
        into leftSecondaryAddress
    from secondaryAddress in leftSecondaryAddress.DefaultIfEmpty()                    
    where
        brokerAccount.AccountID == 100 &&
        primaryAddress.AddressTypeID == 1

答案 1 :(得分:0)

从SQL(带连接)开始时,使用linq连接通常也很自然。但在许多情况下使用导航属性更容易,更短。不幸的是,你没有显示类模型,所以我必须猜测存在哪些导航属性。但它可以是这样的:

var data = 
   from account in dc.Accounts
   where account.AccountID == 100 // where does brokerAccount come from??
   select new {
                Account = account,
                PrimaryAddress =  account.Addresses
                                  .FirstOrDefault(a => a.AddressTypeID == 1),
                SecondaryAddress = account.Addresses
                                  .FirstOrDefault(a => a.AddressTypeID == 2)
              };

看起来比查询短得多,但这是因为您的查询不包含select。所以我希望你可以使用导航属性。它有助于更​​多地关注您想要的数据,而不是 来获取它们。