【发布时间】:2019-09-02 17:02:51
【问题描述】:
我在尝试泛型转换或构建可以转换为所需泛型类型T 的 LINQ 表达式时遇到了困难。
这是失败的例子:
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>>);
}
}
有什么方法可以转换 T 或构建一个 Linq 表达式,将 T 视为 ICompanyLimitedEntity 并在 SQL 服务器上执行查询?
【问题讨论】:
-
你试过
public override void PrerocessFilters<T>(ISpecification<T> specification) where T : ICompanyLimitedEntity吗?这也使得IsAssignableFrom检查变得多余。 -
@Funk 这将是最好的解决方案,如果 T 始终是 ICompanyLimitedEntity,但不能保证是。