This is a spin off from another question I posted a few days ago that was successfully answered but it really didn't get into the underlying issue I was having but wasn't able to express fully in my original query.
I have a table Product. Product is related to ProductDescription in a one-to-many relationship. ProductDescription can have more than one row for each product. It will have multiple rows if there are multiple translations for the description of the product. Product has开发者_如何学Python a many-to-one relationship with Language. Language has a language code (en, es, etc.) as well as a LanguageId (found in ProductDescription as well).
I want to give my users the ability to request a product and further tell the application to only return descriptions for that product in a specific language.
The problem I'm having is that I understand I need to use projection to accomplish the task in the 3rd paragraph of this question. Something like this:
var query = inventoryRepository.Products
.Where(wherePredicate)
.Select( a=> new Product
{
ProductDescriptions = inventoryRepository.ObjectContext.ProductDescriptions
.Where(a => a.Languages.AlternateCode.Equals("en", StringComparison.CurrentCultureIgnoreCase))
});
However I have about 15 properties in the Products table as well as 4 other child tables of Products that need to be loaded for the result set in addition to just the languages piece. Is there any way for me to do eager loading AND projection so that I don't have to go through and map all of these properties and children objects manually? Here is where my code stands right now:
var query = inventoryRepository.ObjectSet
.Include("ProductDescriptions")
.Include("ProductAllowedWarehouses")
.Include("ProductToCategories")
.Include("PriceLevels")
.Include("AttachmentAssociations.Attachment").AsExpandable()
.Where(wherePredicate);
No Select necessary which is really nice. Once I change ProductDescriptions to a projection I add a Select and then I don't get any of the other properties / children populated for free.
I would read this blog about projections+eager loading. You are going to run into issues when it comes to the eager loading. Recommendation is to use a .Any and perform a sub select.
Why can't you just add a filter/where on ProductDescriptions?
var query = inventoryRepository.ObjectSet
.Include("ProductDescriptions")
.Include("ProductAllowedWarehouses")
.Include("ProductToCategories")
.Include("PriceLevels")
.Include("AttachmentAssociations.Attachment").AsExpandable()
.Where(wherePredicate)
.Where(a=>a.ProductDescriptions.Languages.AlternateCode.Equals("en", StringComparison.CurrentCultureIgnoreCase);
精彩评论