【问题标题】:Expression Cast Error - No coercion operator is defined between types表达式转换错误 - 类型之间未定义强制运算符
【发布时间】:2016-11-02 21:53:49
【问题描述】:

在我的数据存储库中,我有一个基类和派生类,如下所示。

public abstract class RepositoryBase<T> : IRepository<T> where T : EntityBase
{
    public async Task<T> FindOneAsync(Expression<Func<T, bool>> predicate)
    {
        List<T> list = await SearchForAsync(predicate);
        return list.FirstOrDefault();
    }
}

public class CommentUrlRepository : RepositoryBase<CommentUrl>, ICommentUrlRepository
{
    public async Task<CommentUrlCommon> FindOneAsync(
        Expression<Func<CommentUrlCommon, bool>> predicate
    )
    {
        Expression<Func<CommentUrl, bool>> lambda = Cast(predicate);
        CommentUrl commentUrl = await FindOneAsync(lambda);
        return MappingManager.Map(commentUrl);
    }

    private Expression<Func<CommentUrl, bool>> Cast(
        Expression<Func<CommentUrlCommon, bool>> predicate
    )
    {
        Expression converted =
            Expression.Convert(
                predicate,
                typeof(Expression<Func<CommentUrl, bool>>)
            );

        // throws exception
        // No coercion operator is defined between types
        return Expression.Lambda<Func<CommentUrl, bool>>(converted, predicate.Parameters);
    }
}

当我点击“Cast”功能时,出现以下错误:

在类型“System.Func`2[CommentUrlCommon,System.Boolean]”和“System.Linq.Expressions.Expression`1[System.Func`2[CommentUrl,System.Boolean]]”之间没有定义强制运算符.

如何转换此表达式值?

【问题讨论】:

  • 你必须拆开并重建表达式,至少通过替换它的参数(可能还有参数上的任何成员访问表达式)。这可能是一项艰苦的工作,而且很容易出错。您可以(并且可能应该)通过公开任何接受表达式的方法来避免这样做。改用更专业的方法(即FindOneAsync(int primaryKey))。

标签: c# linq expression


【解决方案1】:

我认为你想要的无法完成......
查看this question了解更多信息。
如果你很幸运并且你的表达方式很简单,Marc Gravell 的 Convert 方法可能对你有用

还有一个更简单的例子来说明你的问题

using System;
using System.Linq.Expressions;

namespace Program
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Expression<Func<CommentUrlCommon, bool>> predicate = f => f.Id == 1;

            //As you know this doesn't work
            //Expression converted = Expression.Convert(predicate, typeof(Expression<Func<CommentUrl, bool>>));

            //this doesn't work either...
            Expression converted2 = Expression.Convert(predicate, typeof(Expression<Func<CommentUrlCommon, bool>>));

            Console.ReadLine();
        }
    }

    public class CommentUrlCommon
    {
        public int Id { get; set; }
    }

    public class CommentUrl
    {
        public int Id { get; set; }
    }
}

【讨论】:

  • 您提供的链接中提供的解决方案效果很好。谢谢!
  • 直接从 Linq 查询构建 System.Linq.Expressions.Expression 的绝佳示例。以前我试图通过反思来做到这一点,这并不令人愉快
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 1970-01-01
  • 2018-03-15
  • 1970-01-01
相关资源
最近更新 更多