Linq到实体加入

时间:2016-10-13 15:50:54

标签: c# linq-to-entities

我的linqToEntities查询存在问题。查询结果中缺少产品。有没有办法使用linqToEntities表达式正确返回ProductQuantity和Product属性?

    public class ProductQuantity
        {
           public string Id { get; set; } 
           public string SomeProperty { get; set; } 
           public Product Product { get; set; } 
           public Guid ProductId { get; set; } 
        }

        public class Product
        {
           public Guid Id { get; set; } 
           public string SomeProperty { get; set; } 
           //...
        }

        // MyId is the ProductId I need 
        // The following will return all productQuantity detail but the Product property will be null
        var result = myEntities.ProductQuantities.Include(x => x.Product).Where(x => x.ProductId == MyId)

      // The following will work but I want to avoid refilling the object like this :
      var result = myEntities.ProductQuantities.Include(x =>     x.Product).Where(x => x.ProductId == MyId)
.Select(y => new ProductQuantity{ SomeProperty = y.SomeProperty, Product = y.Product});

使用linq实体执行此操作的正确方法是什么?为什么产品不仅仅是随查询返回?

由于

编辑1

当使用多个include时,看起来我的问题与.Include()有关。

只需在前面的示例中为ProductQuantity添加一个类别:

//This will return the product but not the category
   var result = myEntities.ProductQuantities.Include(x => x.Product).Include(x=> x.Category).Single(x => x.ProductId == MyId)

//This will return the category but not the product
   var result = myEntities.ProductQuantities.Include(x => x.Category).Include(x=> x.Product).Single(x => x.ProductId == MyId)

为什么只能使用一个包含且只有第一个包含???????? (在网上看到了大量类似的例子?)

任何帮助?

1 个答案:

答案 0 :(得分:0)

似乎在任何其他包含中使用相同实体时存在问题。 (例如:如果使用相同的实体,则不能同时检索Product.Unit和Product.AlternateUnit,即:unit)我真的不明白为什么,但我使用单独的查询来获取include无法检索的数据。 / p>