Jus*_*tin 5 c# linq generics casting
我陷入尝试泛型转换或构建可以转换为所需泛型类型的LINQ表达式的尝试T。
这是失败的示例:
public override void PreprocessFilters<T>(ISpecification<T> specification)
{
if (typeof(ICompanyLimitedEntity).IsAssignableFrom(typeof(T)))
{
var companyId = 101; // not relevant, retrieving company ID here
// and now I need to call the method AddCriteria on the specification
// as it were ISpecification<ICompanyLimitedEntity>
// which it should be because at this point I know
// that T is ICompanyLimitedEntity
var cle = specification as ISpecification<ICompanyLimitedEntity>;
// ^-- but of course this conversion won't work, cle is null
// what should I do now?
// I need to call it like this:
cle.AddCriteria(e => e.CompanyId == null ||
e.CompanyId == 0 || e.CompanyId == companyId);
// BTW, AddCriteria receives Expression<Func<T, bool>> as an argument
// tried nasty casts inside of the expression - this doesn't throw NullReference
// but it doesn't translate to SQL either - gets evaluated locally in memory, which is bad
specification.AddCriteria(e => ((ICompanyLimitedEntity)e).CompanyId == null ||
((ICompanyLimitedEntity)e).CompanyId == 0 ||
((ICompanyLimitedEntity)e).CompanyId == companyId);
// this one also doesn't work
Expression<Func<ICompanyLimitedEntity, bool>> lex = e => e.CompanyId == null ||
e.CompanyId == 0 || e.CompanyId == companyId;
// it's null again -----------v
specification.AndCriteria(lex as Expression<Func<T, bool>>);
}
}
Run Code Online (Sandbox Code Playgroud)
是否有任何方法可以强制转换T或构建将被T视为ICompanyLimitedEntity并在SQL Server上执行查询的Linq表达式?
以下是构建所需表达式的方法。
首先,使用接口类型参数创建编译时表达式
Expression<Func<ICompanyLimitedEntity, bool>> exprI = e => e.CompanyId == null ||
e.CompanyId == 0 || e.CompanyId == companyId;
Run Code Online (Sandbox Code Playgroud)
然后将主体内的参数替换为新类型的参数T,并使用修改后的表达式作为新 lambda 表达式的主体:
var parameterT = Expression.Parameter(typeof(T), "e");
var bodyT = exprI.Body.ReplaceParameter(exprI.Parameters[0], parameterT);
var exprT = Expression.Lambda<Func<T, bool>>(bodyT, parameterT);
Run Code Online (Sandbox Code Playgroud)
其中是用另一个表达式替换参数的ReplaceParameter典型基础帮助器:ExpressionVisitor
public static partial class ExpressionUtils
{
public static Expression ReplaceParameter(this Expression expression, ParameterExpression source, Expression target)
=> new ParameterReplacer { Source = source, Target = target }.Visit(expression);
class ParameterReplacer : ExpressionVisitor
{
public ParameterExpression Source;
public Expression Target;
protected override Expression VisitParameter(ParameterExpression node)
=> node == Source ? Target : node;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,在通过通用方法创建 Select 后在本地求值后,您仍然需要为什么 Linq“where”表达式中的成员访问表达式修复程序?