【问题标题】:Generic Getter for EntityFramework modelsEntityFramework 模型的通用 Getter
【发布时间】:2017-02-01 00:29:53
【问题描述】:
使用 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();
}
提前谢谢你
【问题讨论】:
标签:
c#
entity-framework
linq
entity-framework-4
【解决方案1】:
泛型定义了一个类型,并且您正在尝试将其用作属性。您最好的选择可能是尝试使用反射(我想不出其他方法可以通过名称获取属性)。
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 中引用它的属性。