【问题标题】:Linq Outer Joins - don't want DefaultIfEmpty, rather want NullIfEmptyLinq 外连接 - 不想要 DefaultIfEmpty,而想要 NullIfEmpty
【发布时间】:2016-11-29 03:01:00
【问题描述】:

所有,

此问题与 Dynamics CRM 2011 Linq 提供程序有关 - 它确实有很多怪癖。但是,我没有标记它,例如我认为这是一个一般的 Linq 问题。

我有一门课——产品。它有一个 Price 类型的属性(比如 ProductPrice)。

我正在 Linq 中对此进行外部联接。 CRM 文档说外部连接是不可能的,但它似乎可以工作(我在这里问的是明显的问题)。

所以说我正在做类似的事情:(为伪 linq 道歉)

        IList<Product> products = (from p in xrmContext.Products 
                                  join pr in xrmContext.Prices
                                  on p.ProductId equals pr.ProductId into prx from prices in prx.DefaultIfEmpty
                                  select new Product { ProductName = p.productName, ProductPrice = new Price { Amount = prices.PriceValue }).ToList();

这在某种程度上很有效。它创建所有产品,无论它们是否具有价格对象。小费顶。

问题在于 DefaultIfEmpty。毫无疑问,如果产品没有价格,则此 DefaultIfEmpty 将创建一个“默认”价格对象……即具有空值的对象。我实际上想要的是没有价格对象 - 即 null,而不是“空白”对象。

这怎么可能?

我通过测试空白价格名称来解决这个问题 - ProductPrice = price.priceName == "" ? null : 新价格 ...

如果能够做 NullIfEmpty 之类的事情,那就太好了。有什么想法吗?

【问题讨论】:

  • LINQ 提供程序特定的,因为例如 LINQ to SQL 确实在这种情况下生成空引用。

标签: linq dynamics-crm-2011


【解决方案1】:

你可以跳过加入:

from p in xrmContext.Products 
let price = xrmContext.Prices.FirstOrDefault(pr => pr.ProductID == p.ProductID)
select new Product()
{ 
    ProductName = p.productName,
    ProductPrice = price != null ? new Price() { Amount = price.PriceValue } : null
}

【讨论】:

    【解决方案2】:

    crm 2011 linq 不支持外连接。 如果您尝试 Amiram 的代码 - 在评估选择时,您会收到错误“产品不包含属性“价格值””。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-07
      • 2013-02-04
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 2015-02-15
      • 2020-04-27
      • 2013-08-29
      相关资源
      最近更新 更多