2012-03-15 24 views
0

在EntityFramework(和生成的LINQ)中有没有一种方法可以针对未硬编码的实体的属性进行查询?使用EF查询编译时未知属性

比方说,可以用于搜索功能的东西。

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

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

你最终为此做了什么?我发现自己需要同样的东西。用于多字段搜索。我正在关注这个例子,我使用EF来代替DataTables,就像他们的例子。 http://demos.telerik.com/aspnet-ajax/controls/examples/integration/gridandcombo/defaultcs.aspx?product=grid – hardba11 2012-06-15 22:40:02

回答

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()); 
} 
+0

可能是linq-to-objects的一个优雅的解决方案。但是,实体框架查询将永远不会转换为SQL。 – 2012-03-15 19:26:13

0

你可以建立手动等于表达这样

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();