表达式强制转换错误-类型之间没有定义强制操作符
本文关键字:操作符 之间 定义 转换 错误 表达式 类型 | 更新日期: 2023-09-27 18:15:57
在我的数据存储库中,我有一个基类和派生类,如下所示。
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. common]之间没有定义强制操作符。'和'System.Linq.Expressions.Expression ' 1[System.Func ' 2[CommentUrl,System.Boolean]]'.
如何转换表达式值?
我认为你想要的东西是做不到的。
查看这个问题了解更多信息。
如果你足够幸运并且你的表达式很简单,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; }
}
}