2016-11-02 7 views
4

私のデータリポジトリには、以下のような基本クラスと派生クラスがあります。私は「キャスト」機能を打つとき式キャストエラー - 型の間に強制演算子が定義されていません

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

私は、次のエラーを取得しています:

No coercion operator is defined between types 'System.Func 2[CommentUrlCommon,System.Boolean]' and 'System.Linq.Expressions.Expression 1[System.Func`2[CommentUrl,System.Boolean]]'.

私は、この式の値をキャストするにはどうすればよいですか?

+0

あなたの問題を示しているあなた

そしてシンプルな例のために働くかもしれません少なくともそのパラメータ(および場合によってはそのパラメータ上の任意のメンバアクセス式)を代入することによって達成される。それは困難な作業であり、間違ってしまうのは非常に簡単です。式を受け入れるメソッドを公開しない* *で公開することはできません。より特殊化されたメソッド(つまり、 'FindOneAsync(int primaryKey)')を使用してください。 –

答えて

1

私はあなたがしたいことができないと思います...
this questionを確認してください。あなたは幸運であり、あなたの表現が単純な場合
は、マルク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; } 
    } 
} 
+0

あなたが提供したリンクで提供されている解決策は素晴らしいものでした。ありがとう! –

関連する問題