0

This is a design question, I have this extension method:

public static IQueryable<R> ToViewModels<T,R>(this IQueryable<T> DBModels_Q)
{
    //calling another method (irrilevant for this question)
    return ToViewModels<T, R>().Invoke(DBModels_Q.AsExpandable());
}

This method works really well if called with:

//db is the EntityFramework context and Employee is the DB table
db.Employee.ToViewModels<DBModels.Employee, ViewModels.Employee>();

I'm wondering if there is a way to use it without specifying the type of T:

db.Employee.ToViewModels<ViewModels.Employee>();

something like How do I get the calling method name and type using reflection? would be usefull.

UPDATE

like suggested the answer was at Partial generic type inference possible in C#?

sadly the only way is to wrap everything and use 2 methods:

public static ViewModelsWrapper<TSource> LoadViewModels<TSource> (this IQueryable<TSource> DBModels_Q)
    {
        return new ViewModelsWrapper<TSource>(DBModels_Q);
    }

    public class ViewModelsWrapper<TSource>
    {
        private readonly IQueryable<TSource> DBModels_Q;
        public ViewModelsWrapper(IQueryable<TSource> DBModels_Q)
        {
            this.DBModels_Q = DBModels_Q;
        }
        public IQueryable<TResult> GetViewModels<TResult>()
        {
            return ToModels<TSource, TResult>().Invoke(this.DBModels_Q.AsExpandable());
        }
    }

using it like

sv.db.Employee.LoadViewModels().GetViewModels<EmployeeModel>();
Community
  • 1
  • 1
Simone
  • 332
  • 4
  • 16
  • You exposed `ToViewModels` method but you call `ToModels`. Are they the same ? – Disappointed Jul 23 '15 at 11:19
  • No. There is no way that the compiler could desume the `R` type without looking inside the method body. – xanatos Jul 23 '15 at 11:19
  • Is your update actually an answer? If so, please move it to one. – Tom Blodget Jul 23 '15 at 20:38
  • Actually I can't see the buttons to confirm the answer... the correct answer would be the one already asked here: http://stackoverflow.com/questions/2893698/partial-generic-type-inference-possible-in-c – Simone Jul 24 '15 at 09:34

0 Answers0