【问题标题】:Linq to SQL and outer applyLinq to SQL 和外部应用
【发布时间】:2011-10-05 03:21:37
【问题描述】:

我正在尝试将“SQL Outer Apply”转换为 Linq。 SQL 是:

select Currencies.Name, Currencies.Sign ,a.ActualPrice 
from Currencies 
outer apply (select CurrencyID,ActualPrice from Prices 
where ProductID=5 and      Currencies.ID=Prices.CurrencyID)a

我尝试了以下 Linq,但得到了一行,而不是 SQL 语句给我的每种货币的一行。

from c in Currencies 
from p in Prices.DefaultIfEmpty()
where p.ProductID.Equals(5) && c.ID==p.CurrencyID
select new {c.Name, p.ActualPrice}

有什么解决办法吗?

【问题讨论】:

标签: sql linq apply outer-join


【解决方案1】:

试试这个:

var result = 
    Currencies.Select(c => new
                      {
                          Name = c.Name, 
                          Sign = c.Sign, 
                          ActualPrice = Prices.Where(p => p.ProductID == 5 && 
                                                          p.CurrencyID == c.ID)
                                              .FirstOrDefault()
                      });

我不确定这是否返回正确的结果,因为我不知道当outer apply 中的子选择返回多行时会发生什么...

【讨论】:

  • OUTER APPLY 等价于LEFT JOIN,但它是一个子查询的函数,它能够从它所连接的记录中接受值。
  • 谢谢丹尼尔。有点重新编码改变了,但这就是想法。 ' select new ProductPrices { CurrencyName = c.Name, Sign = c.Sign, ActualPrice = (from p in ctx.Prices where p.ProductID == productId && p.CurrencyID == c.ID select p.ActualPrice).FirstOrDefault( ), 选择 p.FullPrice).FirstOrDefault() ?? 0 }'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 2011-10-14
  • 1970-01-01
相关资源
最近更新 更多