使用EF查询编译时未知属性

时间:2012-03-15 07:55:43

标签: entity-framework-4.1

EntityFramework(和生成的LINQ)中是否有一种方法可以查询非硬编码实体的属性?

让我们说,可以用于搜索功能。

public IList<Entity> Search (string propertyName, object value) {

    // something that'll do the following
    return context.Set<Entity>()
        .Where(x => x.propertyName == value)
        .ToList()
        ;
}

2 个答案:

答案 0 :(得分:0)

Property Descriptor怎么样?

以下代码似乎可以满足您的需求:

string propertyName = "Length";
List<string> testList = new List<string>();

testList.Add("String1");
testList.Add("String10");
testList.Add("String100");
testList.Add("String1000");

System.ComponentModel.PropertyDescriptorCollection props = System.ComponentModel.TypeDescriptor.GetProperties(typeof(string));

System.ComponentModel.PropertyDescriptor desc = props.Find(propertyName, false);

IEnumerable<object> obj = from env in testList
             select desc.GetValue(env);

foreach (object it in obj)
{
    Console.WriteLine(it.ToString());
}

答案 1 :(得分:0)

您可以像这样手动构建equals表达式

private static Expression<Func<TEntity, bool>> BuildEqualExpression<TEntity>(string propertyName, object value)
{
    var param = Expression.Parameter(typeof(TEntity), "x");
    var body = Expression.MakeBinary(ExpressionType.Equal,
        Expression.Property(param, propertyName), Expression.Constant(value));

    return Expression.Lambda<Func<TEntity, bool>>(body, new ParameterExpression[] { param });
}

然后在LINQ查询中使用它

var expression = BuildEqualExpression<TEntity>(propertyName, value);
return context.Set<TEntity>().Where(expression).ToList();