Is it possible to parse generic type T from predicate expression and convert it back to another type and then create new expression by using converted type?
I'm doing the conversion from T to DTO.Company and after that I should do the mapping from DTO.Company to DAL.Company. In below code example I'm trying to do conversion but first I need to know that is it even possible and secondly I need to know how to convert DTO.Company to DAL.Company inside the predicate parameters before setting the bar variable.
// 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));
}