0

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));
    }
soreal
  • 264
  • 1
  • 9
  • There was this question: http://stackoverflow.com/questions/42902164/how-to-map-expressionfunctentity-bool-to-expressionfunctdbentity-bool/42904029#42904029 Take a look if it is enough for you – xanatos Mar 28 '17 at 12:54

1 Answers1

1

Ok, I changed logic a little bit.

First logic was:

  1. Service layer takes only DTO parameters and returns only DTO objects.
  2. Repository layer takes only DTO parameters and predicate parameters are only DTO and returns only DTO pbjects.

Now it's:

  1. Service layer takes only DTO parameters and returns only DTO objects.
  2. Repository layer takes only DTO paramaters and predicate parameters are only DAL and returns only DTO objects.
soreal
  • 264
  • 1
  • 9