ジェネリック式に関して問題があります。
があり、Expression<Func<T, bool>>
を に変換しExpression<Func<T, bool>>
たいExpression<Func<Y, bool>>
。クラスのオブジェクトはT
、クラス Y と同じプロパティを持ちます。
これを解決する方法を知っている人はいますか?
ジェネリック式に関して問題があります。
があり、Expression<Func<T, bool>>
を に変換しExpression<Func<T, bool>>
たいExpression<Func<Y, bool>>
。クラスのオブジェクトはT
、クラス Y と同じプロパティを持ちます。
これを解決する方法を知っている人はいますか?
これを行うための「推奨される」方法は、関心のあるプロパティを含む Interface を使用することです。
interface IMyProp
{
string SomeProp {get;}
}
class T : IMyProp
{
public string SomeProp
{
get
{
//Some complicated logic
}
}
}
class Y : IMyProp
{
public string SomeProp {get; set;}
}
式をコーディングするだけですExpression<Func<IMyProp, bool>>
ただし、常にこれを実行できるとは限らないことは理解できます。このような状況では、AutoMapperなどのライブラリを使用できます。
class T
{
public string SomeProp
{
get
{
//Some complicated logic
}
}
}
class Y
{
public string SomeProp {get; set;}
}
//Some initiation code somewhere else in your project
public static void InitializeMappings()
{
Mapper.CreateMap<T, Y>();
}
public static IQueryable<Y> FilterOnTAndMapToY(IQueryable<T> source, Expression<Func<T,bool>> filter)
{
return source.Where(filter).Project().To<Y>();
}
Expression<Func<T, bool>>
これで toが正確に変換されるわけではありませんExpression<Func<Y, bool>>
が、T
式を使用してY
、フィルタリングが適用された後に結果を取得することができます。
AutoMapper のQueryable Extensionsが機能する方法は、 LinqToEntities を実行しているときにすべてのサーバー側T
で発生するクエリとキャストです。Y
だからあなたもできる
public static IQueryable<Y> MultiFilterCast(IQueryable<T> source, Expression<Func<T,bool>> tTypeFilter, Expression<Func<Y,bool>> yTypeFilter)
{
var filteredStage1 = source.Where(tTypeFilter);
var castToY = filteredStage1.Project().To<Y>();
var filteredStage2 = castToY.Where(yTypeFilter);
return filteredStage2;
}
両方ともtTypeFilter
、yTypeFilter
結果セットを取得する前にサーバー側に適用されます。