Expression Cast Error - coercion operator is not defined between types

In my data repository, I have a base class and a derived class, as shown below.

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

When I hit the Cast function, I get the following error:

The coercion operator is not defined between the types "System.Func 2[CommentUrlCommon,System.Boolean]' and 'System.Linq.Expressions.Expression1 [System.Func`2 [CommentUrl, System.Boolean]]".

How can I assign this value to an expression?

+4
source share
1 answer

, ...
.
, , 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; }
    }
}
+1

Source: https://habr.com/ru/post/1659658/


All Articles