2013-02-03 2 views
0

내 도메인의 모든 DateTime을 SQL Server에서 datetime2로 강제 설정하려고합니다. 나는 내가 사용할 수 있습니다 :EF5 코드 첫 번째 datetime2, linq 식 작성

Property(x => x.Field).HasColumnType("datetime2"); 

내 EntityTypeConfiguration 파생 클래스에서.

하지만 "덜 자세한"코드를 작성하고 싶습니다.

public static void SetDateTimeColumnType<T>(EntityTypeConfiguration<T> etc) where T : class { 
    Type t = typeof(T); 
    foreach (PropertyInfo pi in t.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { 
     if (pi.PropertyType.Name == "DateTime") { 
      etc.Property(x => (DateTime)pi.GetValue(x)).HasColumnType("datetime2"); 
     } 
    } 
} 

그러나 나는 다음과 같은 예외를 얻을 : 나는 다음과 같은 시도

The expression 'x => Convert(value(EFVIPRepository.ContextUtilities+<>c__DisplayClass0`1[ValkirIP.Domain.Entities.IPRight]).pi.GetValue(x))' 
is not a valid property expression. 
The expression should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'. 
Use dotted paths for nested properties: C#: 't => t.MyProperty.MyProperty' VB.Net: 'Function(t) t.MyProperty.MyProperty'. 

나는 내 진짜 질문은 가능하면 속성의 이름에서 "속성 expresssion"을 구축하는 방법을 생각합니다.

Impossible d'effectuer un cast d'un objet de type 'System.Linq.Expressions.PropertyExpression' en type 'System.Linq.Expressions.Expression`1[System.Func`2[ValkirIP.Domain.Entities.IPRight,System.DateTime]]'. 

답변

1

당신에게 :

===== 편집 =====가

나는 또한 다음을 제외하고

Expression expr = Expression.Property(System.Linq.Expressions.Expression.Variable(t), pi); 
etc.Property((Expression<Func<T, DateTime>>)expr).HasColumnType("datetime2"); 

을 시도 사전에 감사합니다 올바른 Expression Tree을 작성해야합니다.

이 시도 :

public static void SetDateTimeColumnType<T>(EntityTypeConfiguration<T> etc) where T : class 
{ 
    Type t = typeof(T); 
    foreach (PropertyInfo pi in t.GetProperties(BindingFlags.Public | BindingFlags.Instance)) 
    { 
     if (pi.PropertyType.Name == "DateTime") 
     { 
      var parameter = Expression.Parameter(t, "x"); 
      var property = Expression.Property(parameter, pi.Name); 
      var lmbd Expression.Lambda<Func<T, DateTime>>(property, parameter); 
      etc.Property(lmbd).HasColumnType("datetime2"); 
     } 
    } 
} 
관련 문제