Search code examples
c#entity-frameworklinqentity-framework-4

Generic Getter for EntityFramework models


Using Entity Framework v4, I'd like to create in C# a generic getter for my model classes. I don't know if that is possible and how to implement it.

The problem I'm facing is how to map the attribute name in the Linq query

For example:

public static List<T> GetModelsByAttribute<T,R>(R attribute, string attributeName)
    {
        return new OracleTestConnection().T.Where(d => d.attributeName == att).ToList();
    }

Thank you in advance


Solution

  • Generics define a Type, and you are trying using it as a property. It's likely that your best bet would be to try to use reflection (no other way I can think of with which you could get a property by the name).

    public static List<T> GetModelsByAttribute<T,R>(string propertyName, R attribute, string attributeName) where T : YourAttributeClass
    {
        var connection = new OracleTestConnection();
        var property = (List<T>)connection.GetType().GetProperty(propertyName).GetValue(connection, null);
        return property.Where(d => d.attributeName == att).ToList(); // assuming your class YourAttributeClass has attributeName property
    }
    

    In this case you would pass a property name, and assuming that the property is derived from YourAttributeClass, you can reference its' properties in the LINQ.