在我的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);
}
}
当我点击“投射”功能时,我收到以下错误:
在类型System.Func
2[CommentUrlCommon,System.Boolean]' and 'System.Linq.Expressions.Expression
1 [System.Func`2 [CommentUrl,System.Boolean]]'之间没有定义强制运算符。
如何转换此Expression值?
答案 0 :(得分:3)
我认为你想做什么是不可能的...... 请查看this question了解更多信息 如果你很幸运并且你的表达很简单,Marc Gravell的转换方法可能适合你
一个更简单的例子来证明你的问题
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; }
}
}