2012-03-15 4 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

이 일을 위해 무엇을 마쳤습니까? 나는 같은 것을 필요로하는 자신을 찾는다. 다중 필드 검색의 경우. 나는이 예제를 따르고 있는데, 나는 그들의 예제처럼 DataTables 대신에 EF를 사용하고있다. http://demos.telerik.com/aspnet-ajax/controls/examples/integration/gridandcombo/defaultcs.aspx?product=grid – hardba11

답변

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의 멋진 솔루션이 될 수 있습니다. 그러나 Entity Framework 쿼리는 절대로 SQL로 변환되지 않습니다. –

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(); 
관련 문제