0

我需要将此 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

我应该改变什么?

4

2 回答 2

0

如果您使用匿名类型加入多列,则可以改进查询:

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
于 2013-02-11T17:20:30.693 回答
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. 所以我希望你可以使用导航属性。它有助于更​​多地关注想要的数据,而不是如何获取它们。

于 2013-02-12T18:53:12.927 回答