EntityFramework模型的通用Getter

时间:2016-09-23 08:08:23

标签: c# entity-framework linq entity-framework-4

使用Entity Framework v4,我想在C#中为我的模型类创建一个通用的getter。我不知道这是否可能以及如何实施。

我面临的问题是如何在Linq查询中映射属性名称

例如:

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

提前谢谢

1 个答案:

答案 0 :(得分:1)

泛型定义一个Type,您正在尝试将其用作属性。你可能最好的选择是尝试使用反射(没有其他方法我可以想到你可以通过名称得到一个属性)。

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
}

在这种情况下,您将传递属性名称,并假设该属性派生自YourAttributeClass,您可以在LINQ中引用其属性。