【问题标题】:Entity Framework Repository Not Working with Multi-Level .Include()实体框架存储库不适用于多级 .Include()
【发布时间】:2014-10-13 21:05:01
【问题描述】:

我正在处理一个其他人使用实体框架设置存储库类的大型项目。我知道有些问题可能与自定义代码有关,但谁能帮我确定下一步该往哪里看?

我正在尝试编写这个查询:

List<ProductItem> addedProductItems =
    repository.Query<ProductItem>()
        .Include(pi => pi.Product)
        .Include(pi => pi.ProductItemVendors.Select(v => v.ProductPricings))
        .Where(pi => !pi.IsDeleted && productIdSortOrder.Keys.Contains(pi.ProductId))
        .AsEnumerable()
        .OrderBy(pi => productIdSortOrder[pi.ProductId])
        .ToList();

但是带有第二个.Include() 的行会产生以下错误。 (第一个.Include() 工作正常。):

错误 5 类型“System.Collections.Generic.IEnumerable>”不能用作泛型类型或方法“VIP.Domain.Repository.IRepositoryObjectQuery.Include(System.Linq.Expressions.Expression”中的类型参数“TEntity2” >)'。没有从“System.Collections.Generic.IEnumerable>”到“Leo.Domain.ILeoDomainModelItem”的隐式引用转换。

这是包含Include() 的接口的定义方式:

public interface IRepositoryObjectQuery<TEntity, TEntityMarker>
    : IOrderedQueryable<TEntity>, IQueryable<TEntity>, IEnumerable<TEntity>, IOrderedQueryable, IQueryable, IEnumerable, IListSource
    where TEntity : TEntityMarker
{
    IRepositoryObjectQuery<TEntity, TEntityMarker> Include<TEntity2>(IRepositoryPropertyChain<TEntity, TEntity2> propertyChain) where TEntity2 : TEntityMarker;
    IRepositoryObjectQuery<TEntity, TEntityMarker> Include<TEntity2>(Expression<Func<TEntity, TEntity2>> propertyGetter) where TEntity2 : TEntityMarker;
    IRepositoryObjectQuery<TEntity, TEntityMarker> Include<TEntity2>(Expression<Func<TEntity, ICollection<TEntity2>>> propertyGetter) where TEntity2 : TEntityMarker;
}

有人能看出这里可能是什么问题吗?

【问题讨论】:

  • 模型是如何定义的?特别是 ProductItem、ProductItemVendors 和 ProductPricings 是如何定义和关联的?
  • 什么是ILeoDomainModelItem
  • @JotaBe:我认为这很明显。 ProductPricing 具有 ProductItemVendors 的外键,ProductItemVendors 具有 ProductItem 的外键。
  • @DavidG:它实际上只是一个标记类来显示某物是一个实体。
  • 请显示ProductItem 类,特别是。 ProductItemVendors的代码。它似乎不是映射属性。

标签: c# entity-framework generics repository


【解决方案1】:

表达式的结果

pi => pi.ProductItemVendors.Select(v => v.ProductPricings)

不是ICollection&lt;T&gt; 也可能不是IRepositoryPropertyChain,所以唯一可以使用它的重载是

IRepositoryObjectQuery<TEntity, TEntityMarker> Include<TEntity2>(
    Expression<Func<TEntity, TEntity2>> propertyGetter) 
    where TEntity2 : TEntityMarker;

由于类型约束,TEntity2 必须派生自/实现TEntityMarker(显然是Leo.Domain.ILeoDomainModelItem)。 IEnumerable&lt;TypeOfProductPricings&gt;(包含表达式的结果)没有实现该接口。

【讨论】:

    猜你喜欢
    • 2010-12-02
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2011-06-16
    • 1970-01-01
    相关资源
    最近更新 更多