Returning Generic T RRS feed

  • Question

  • I need to return a product according the type I specify on T.
    However when I need to use linq (firstOrDefault) sintax, I need to specify the Db.<GenericThatIdefiniedOnT)

    How can I get that ?

    public static T ReturnProduct<T>(int position)
        var product = Db.getType<T>.FirstOrDefault(p => p.ProductId == position);
        return product;

    Monday, September 8, 2014 5:36 PM


  • There is no ProductId property of the type T unless you constrain the the type parameter to be of a specific type that contains a ProductId property:

    public static T ReturnProduct<T>(int position) where T : Product
                var product = context.Set<T>().FirstOrDefault(p => p.ProductId == position);
                return product;

    But then you can of course only use the ReturnProduct method for T = Product, i.e. for the Product class and all classes that inherit from the Product class.

    If you want a truly generic method, it should accept the filter expression as a parameter:

    public static T ReturnProduct<T>(Func<T, bool> where)
         var product = context.Set<T>().FirstOrDefault(where);
         return product;

    You then specify the filter condition when you call the method:

    int position = 10;
    Product p = ReturnProduct<Product>(x => x.ProductId == position);

    Please refer to my blog post about how to create a generic data access layer using Entity Framework for more information: http://blog.magnusmontin.net/2013/05/30/generic-dal-using-entity-framework/

    • Marked as answer by Fred Bao Tuesday, September 16, 2014 9:31 AM
    Monday, September 8, 2014 9:17 PM