Problem to use generic method inside another generic method. RRS feed

  • Question

  • Hi

    I have a generic method as follow :

    public static T GetObjectGraph<T, TDetails, TField>(DbContext dbContext, Expression<Func<T, TDetails>> details, Expression<Func<T, TField>> field, TField value) where T : class
                var p = field.Parameters[0];
                var eq = Expression.Equal(field.Body, Expression.Constant(value));
                var expr = Expression.Lambda<Func<T, bool>>(eq, p);
                return dbContext

    Which using in my code as follow :

    var existingPackageHeader = HelperMethods.GetObjectGraph(_dbContext, (DefaultVisitProductHeaders h) => h.DefaultVisitProductDetails, (DefaultVisitProductHeaders h) => h.DefaultVisitProductHeaderRowID, packageHeader.DefaultVisitProductHeaderRowID);

    The above code works. My problem is that when i use my method in another generic method as follow :

    public static void AttachDetailsListToDbContext<T, TDetails, TField>(HttpContext context, string strName, DbContext dbContext, object masterObjectGraph, Expression<Func<T, TDetails>> details, Expression<Func<T, TField>> field, TField value, InternalHelperAction action)
                List<T> lstPackageDetails = HelperMethods.DeserializeListFromTempData<T>(context, strName);
                var trackedEntries = dbContext.ChangeTracker.Entries().ToList();
                foreach (var entry in trackedEntries)
                    entry.State = EntityState.Detached;            
                dbContext.Entry(existingPackageHeader).CurrentValues.SetValues(masterObjectGraph); // Compile time error!

    I'm facing the following compile error :

    The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'HelperMethods.GetObjectGraph(DbContext, Expression>, Expression>, TField)'

    Where is the problem & how to solve it?

    Thanks in advance


    Monday, June 1, 2020 5:33 PM

All replies

  • Just add where T : class at the end of the method declaration, in the same way that you have where T : class at the end of GetObjetClass.
    Monday, June 1, 2020 6:47 PM
  • Hi Hamed_1983,
    If you put constraints on generic classes or methods, all other generic classes or methods that use it must have at least these constraints.
    So as Alberto Poblacion said, you can add where T : class at the end of the AttachDetailsListToDbContext method.
    For a better understanding, you can refer to Dennis answer.
    Best Regards,
    Daniel Zhang

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, June 2, 2020 2:05 AM