表达式转换错误 - 类型之间没有定义强制运算符

Teo*_*ahi 7 c# linq expression

在我的Data Repository中,我有一个基类和派生类,如下所示.

 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我点击"投射"功能时,我收到以下错误:

在类型System.Func 2[CommentUrlCommon,System.Boolean]' and 'System.Linq.Expressions.Expression1 [System.Func`2 [CommentUrl,System.Boolean]]' 之间没有定义强制运算符.

如何转换此Expression值?

Geo*_*vos 3

我认为你想要的东西无法完成......
检查此问题以了解更多信息。
如果您幸运并且您的表达式很简单,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; }
    }
}
Run Code Online (Sandbox Code Playgroud)