c# – 查询的结果类型既不是EntityType,也不是具有实体元素类型的CollectionType

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

最后一行抛出:

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.

我已经设法找到很少甚至没有解释为什么会发生这种情况.有帮助吗?

最佳答案 您的课程在产品和本地化之间是否存在物理关系?如果他们这样做,你不应该使用join.此外,您必须在选择之前调用include.

试试这个:

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();
点赞