简体   繁体   English

Linq加入实体

[英]Linq to entities with join

I'm having some problem with my linqToEntities query. 我的linqToEntities查询有问题。 The Product is missing in the query result. 查询结果中缺少产品。 Is there any way to return the ProductQuantity with the Product property correctly with a linqToEntities expression? 有什么方法可以使用linqToEntities表达式正确返回具有Product属性的ProductQuantity吗?

    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});

What is the proper way to do this with linq to entities? 使用linq对实体执行此操作的正确方法是什么? Why the product is not just simply returned with the query ? 为什么产品不只是随查询一起返回?

Thanks 谢谢

EDIT 1 编辑1

Look like my problem is releated to .Include() when using more than one include. 看起来我的问题在使用多个include时与.include()有关。

Just add a Category to ProductQuantity in the preceding example : 只需在前面的示例中向ProductQuantity添加一个Category即可:

//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)

Why only one include can be used and only the first one is working??????? 为什么只能使用一个include,而只有第一个可以使用??????? (a saw tons of similar example on the net?) (网上有很多类似的例子吗?)

Any help? 有什么帮助吗?

Seems like there is a problem when the same entity is used in any other include. 在其他包含中使用同一实体时,似乎存在问题。 (ex: Product.Unit and Product.AlternateUnit cannot be retreived at the same time if the same entity is used ie:unit) I dont really understand why but I use separate query to fetch the data that cannot be retrieved by the include. (例如:如果使用相同的实体(即:unit),则无法同时检索Product.Unit和Product.AlternateUnit。)我真的不明白为什么,但是我使用单独的查询来获取包含文件无法检索的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM