【问题标题】:csharp generic repository: could not use Select() method with IEnumerable (error: explicit cast needed)csharp 通用存储库:无法将 Select() 方法与 IEnumerable 一起使用(错误:需要显式转换)
【发布时间】:2023-03-08 21:47:01
【问题描述】:

我使用 Csharp 和 mariaDb 已经 6 个月了。在只使用 POC 之后,我开始对通用存储库、EF6 和函数式编程产生兴趣。我实际上正在为我的应用程序做一些重构。

在我的通用存储库中,我有以下代码:

public IEnumerable<TType> FindColumn<TType>(Expression<Func<TEntity, TType>> selection, Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, TType>> OrderExpression)
        {
            return Context.Set<TEntity>().Where(predicate).OrderBy(OrderExpression).Select(selection).ToList();
        }

我在非泛型仓库中这样操作这段代码:

public IEnumerable<chantiers> GetAllChantiersAsc()
        {
            return FindColumn(d => d.NomChantier, d => d.NomClient.Equals(clients.NomClient), d=>d.NomChantier);
        }

我有这个错误:

无法将类型“System.Collections.Generic.IEnumerable”隐式转换为 'System.Collections.Generic.IEnumerable'。 存在显式转换(您是否缺少演员表?)

在我的应用程序中,我想要一个通用方法来从我的 EF6 实体中检索列。 感谢您的帮助。

【问题讨论】:

  • d=&gt;d.NomChantier - 看起来您选择的是字符串名称,但您的方法期望返回chantiers 列表。

标签: c# linq generics entity-framework-6 ienumerable


【解决方案1】:

首先你忘了在 FindColumn 的函数标识符中添加 TEntity:

public IEnumerable<TType> FindColumn<TEntity, TType>(...)

当然,您已经尝试通过完全指定所有类型来找出哪些参数不正确:

public IEnumerable<Chantiers> GetAllChantiersAsc()
{
    Expression<Func<myEntityType, Chantiers>> selection = d => d.NomChantier;
    Expression<Func<myEntityType, bool>> predicate = d => d.NomClient.Equals(clients.NomClient);
    Expression<Func<myEntityType, Chantiers>> orderExpression = d=>d.NomChantier;
    IEnumerable<Chantiers> result = FindColumn<myEntityType, Chantiers>(
         selection,
         predicate,
         orderExpression);
     return result;
}

我相信您的编译器会告诉您哪些参数的类型不正确。我的猜测是 nomChantiers 是你的问题,因为它似乎是一个名称,而不是 Chantiers

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多