2017-09-11 4 views
0

쿼리 트리에 Entity Framework를 쿼리하는 방법을 알고 있습니다.LINQ to Entities 용 표현식에서 DateTime을 사용하는 방법은 무엇입니까?

 string propertyName = "Name"; 
     string keyword = "Methanol"; 

     ParameterExpression parameter = Expression.Parameter(typeof(Chemical), "x"); 

     MemberExpression me = Expression.Property(parameter, propertyName); 
     ConstantExpression constant = Expression.Constant(keyword, typeof(string)); 
     BinaryExpression body = Expression.Equal(me, constant); 
     var isEqualExpressionTree = Expression.Lambda<Func<Chemical, bool>>(body, new[] { parameter }); 
     Expression<Func<Chemical, bool>> funcExpression = (Expression<Func<Chemical, bool>>)isEqualExpressionTree; 

     using (var mLEntities = new myLab02Entities1()) 
     { 
      var cl = mLEntities.Chemicals.AsQueryable().Where(funcExpression).ToList();  
      return cl; 

     } 

"이름"은 SQL 데이터베이스의 필드이며 "메탄올"을 선택해야합니다. 내부에 람다가 있습니다 : {x => (x.Name == "Methanol")}. 이제 데이터베이스의 DateTime 필드를 테스트하려고하지만 Date 부분 만 테스트합니다. 그래서 내 람다는

{x => DbFunctions.TruncaateTime (x.EntryDate) == DbFunction.TruncateTime (testDate)}이 될 것입니다. 이것은 그대로 작동하지만 이것을 표현식으로 어떻게 변환 할 수 있습니까? 감사합니다, Hucky

답변

0
string propertyName = "EntryDate"; 
DateTime testDate = DateTime.Now;    

ParameterExpression parameter = Expression.Parameter(typeof(Chemical), "x"); 
MemberExpression me = Expression.Property(parameter, propertyName); 
var ce = Expression.Convert(me, typeof(DateTime?)); 
MethodCallExpression mc = Expression.Call(null, typeof(DbFunctions).GetMethod("TruncateTime", new Type[] { typeof(DateTime?) }), ce); 
ConstantExpression constant = Expression.Constant(testDate, typeof(DateTime?)); 
BinaryExpression body = Expression.Equal(mc, constant); 
var isEqualExpressionTree = Expression.Lambda<Func<Chemical, bool>>(body, new[] { parameter }); 
Expression<Func<Chemical, bool>> funcExpression = (Expression<Func<Chemical, bool>>)isEqualExpressionTree; 
+0

안녕하세요 Akos, 답장을 보내 주셔서 감사합니다. Typeof (DbFunctions)에 대한 오류가 발생합니다. 유형 또는 네임 스페이스 "DbFunctions"을 찾을 수 없습니다. 이 솔루션의 다른 프로젝트에서도 가능하지만 "System.Data.Entity 사용"을 최근 프로젝트에 추가 할 수 없습니다. 나는 여기서 무슨 일이 일어나고 있는지 알아 내려고 노력한다. – Hucky

+0

EntityFramework 너겟이 설치되어 있습니까? –

+0

설치되었지만 다시 설치하려고합니다. – Hucky