【问题标题】:Left Join in Entity Framework实体框架中的左连接
【发布时间】:2013-05-03 14:06:24
【问题描述】:

我正在尝试将此 SQL 转换为 Entity Framework LINQ,但不起作用。

我的 SQL 代码:

SELECT
    s.Id,
    s.OriginalPhotoBlobId,
    s.PhotoBlobExtension,
    ISNULL(s.ProductSkuKey, p.[Key]) as [Key],
    p.Name,
    ISNULL(sp.Price, 0) as [Price],
    sp.PriceList_Id
FROM SKUs s
INNER JOIN Products p on p.Id = s.Product_Id
LEFT JOIN SKUPrices sp on sp.SKU_Id = s.Id

我的实体框架代码:

 var db = this.Context;
 var prices = from s in db.SKUs
              join p in db.Products on s.Product equals p
              join sp in db.SKUPrices on s equals sp.SKU into gj
              from spss in gj.DefaultIfEmpty()
              select new PriceListItem
              {
                 Id = s.Id,
                 BlobId = s.OriginalPhotoBlobId,
                 BlobExtension = s.PhotoBlobExtension,
                 Key = ((s.ProductSkuKey == null || s.ProductSkuKey.Trim() == string.Empty) ? p.Key : s.ProductSkuKey),
                 Name = p.Name,
                 Price = (spss == null ? default(double) : spss.Price),
              };

【问题讨论】:

  • 你能解释一下通过精确转换来达到什么目标吗?例如,通过使用包含,您不必使用这样的连接。
  • 您能解释一下不工作是什么意思吗?

标签: c# sql linq frameworks entity


【解决方案1】:

我认为你应该使用navigation 属性。导航属性用于导航数据中的关系。

【讨论】:

    【解决方案2】:

    尝试加入属性而不是类

    var prices = from s in db.SKUs
                  join p in db.Products on s.Product_Id equals p.Id 
                  join sp in db.SKUPrices on sp.SKU_Id = s.Id into gj
                  from sp in gj.DefaultIfEmpty()
                  select new PriceListItem
                  {
                     Id = s.Id,
                     BlobId = s.OriginalPhotoBlobId,
                     BlobExtension = s.PhotoBlobExtension,
                     Key = ((s.ProductSkuKey == null || s.ProductSkuKey.Trim() == string.Empty) ? p.Key : s.ProductSkuKey),
                     Name = p.Name,
                     Price = (sp == null ? default(double) : sp .Price),
                  };
    

    【讨论】:

      猜你喜欢
      • 2011-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多