简体   繁体   中英

Linq to entities with join

I'm having some problem with my linqToEntities query. 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?

    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? Why the product is not just simply returned with the query ?

Thanks

EDIT 1

Look like my problem is releated to .Include() when using more than one include.

Just add a Category to ProductQuantity in the preceding example :

//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??????? (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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