iuliu.net
iuliu.net

Reputation: 7145

The result type of the query is neither an EntityType nor a CollectionType with an entity element type

var myQuery = from product in _repository.Query()
                      join prodLocalization in _repoProductLocalization.Query()
                      on product.Id equals prodLocalization.ProductId
                      select new { Product = product, Localization = prodLocalization };
myQuery = myQuery.Include(x => x.Product.Customer);
var prods = myQuery.ToList();

Last line throws:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: The result type of the query is neither an EntityType nor a CollectionType with an entity element type. An Include path can only be specified for a query with one of these result types.

I've managed to find little to no explanation on why this happens. Any help?

Upvotes: 4

Views: 4306

Answers (2)

Omarkth
Omarkth

Reputation: 21

I just ran into a similar problem. This happened because the returned type from the first query is "Anonymous", and the Include method can't determine the right path of the needed property to retrieve it ("Customer" in your case).

The only workaround I found is to discard the "Include" method and return the needed navigation properties within the Anonymous type object.

Try this:

var myQuery = from product in _repository.Query()
              join prodLocalization in _repoProductLocalization.Query()
                  on product.Id equals prodLocalization.ProductId
              select new 
              { 
                 Product = product,
                 Customer = product.Customer,
                 Localization = prodLocalization 
              };

var prods = myQuery.ToList();

You can also add this:

var customerProds = prods.Select(i => {
                        var item = new { i.Product, i.Localization };
                        item.Product.Customer = i.Customer;
                        return item;
                    })
                    .ToList();

Upvotes: 0

Fabio
Fabio

Reputation: 11990

Do your classes have physical relation between Product and Localization? If they do, you shouldn't use join. In addition, you must call include before the selection.

Try this:

var myQuery = from product in _repository.Query()
                  .Include(x => x.Product.Customer)
                  .Include(x => x.Product.Localization)
              select new 
              { 
                 Product = product, 
                 Localization = product.Localization 
              };

var prods = myQuery.ToList();

Upvotes: 4

Related Questions