是否可以从谓词表达式解析泛型类型T并将其转换回另一种类型,然后使用转换后的类型创建新表达式?
我正在从T转换为DTO.Company,之后我应该从DTO.Company到DAL.Company进行映射。在下面的代码示例中,我尝试进行转换但首先我需要知道它是否可能,其次我需要知道如何在设置bar变量之前将DTO.Company转换为谓词参数内的DAL.Company。
// This works!!!! But I want to make it generic as possible!
public T Fetch<T>(Expression<Func<DAL.Company, bool>> predicate) where T : class
{
var typeOfT = typeof(T);
if (typeOfT != typeof(DTO.Company))
{
return null;
}
var companies = _dbContext.Companies.Where(predicate);
var ret = new Collection<DTO.Company>();
foreach (var company in companies)
{
ret.Add(company.ConvertToDataTransferObject());
}
return (T)Convert.ChangeType(ret, typeof(T));
}
// This does not work!!!
public T Fetch<T>(Expression<Func<T, bool>> predicate) where T : class
{
var typeOfT = typeof(T);
if (typeOfT != typeof(DTO.Company))
{
return null;
}
var foo = Expression.Convert(predicate.Body, typeof(bool));
//Below I'm getting Exception thrown: 'System.ArgumentException' in System.Core.dll
//Additional information: ParameterExpression of type 'DTO.Company' cannot be used for delegate parameter of type 'DAL.Company'
var bar = Expression.Lambda<Func<DAL.Company, bool>>(foo, predicate.Parameters);
var companies = _dbContext.Companies.Where(bar);
var ret = new Collection<DTO.Company>();
foreach (var company in companies)
{
ret.Add(company.ConvertToDataTransferObject());
}
return (T)Convert.ChangeType(ret, typeof(T));
}
答案 0 :(得分:1)
好的,我改变了一点逻辑。
第一个逻辑是:
现在是: