2013-02-12 84 views
2

我動態執行基於我的POCO類屬性流利的映射和我有.Property情況下工作正常,但炸燬嘗試運行的結尾。可以忽略()方法:如何使用反射調用DbModelBuilder.Entity <T> .Ignore(x => x.Property)?

private void AddEntities(DbModelBuilder modelBuilder) 
{ 
    var entityMethod = typeof(DbModelBuilder).GetMethod("Entity"); 
    foreach (var entityType in EntityBaseTypes) 
    { 
     dynamic entityConfiguration = entityMethod.MakeGenericMethod(entityType).Invoke(modelBuilder, new object[] { }); 
     foreach (PropertyInfo propertyInfo in entityType.GetProperties().Where(x => x.CanWrite)) 
     { 

      foreach (var attribute in propertyInfo.GetCustomAttributes()) 
      { 
       LambdaExpression propertyLambda = PropertyGetLambda(entityType, propertyInfo.Name, typeof(string)); 
       string attributeName = attribute.GetType().Name; 
       if (attributeName == "NotMappedAttribute") 
       { 
        MethodInfo ignoreMethod = (MethodInfo)entityConfiguration.GetType().GetMethod("Ignore");        
//BLOWS UP HERE: Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true 
        ignoreMethod.Invoke(entityConfiguration, new[] { propertyLambda }); 

       } 
       else if (attributeName == "ColumnAttribute") 
       { 
        dynamic column = attribute; 
        var propertyMethod = entityConfiguration.GetType().GetMethod("Property", new Type[] { propertyLambda.GetType() }); 
        var entityProperty = (PrimitivePropertyConfiguration)propertyMethod.Invoke(entityConfiguration, new[] { propertyLambda }); 
//WORKS FINE: 
        entityProperty.HasColumnName(column.Name); 
       } 
      } 
     } 

    } 
} 

我覺得類型.gnore()方法參數所需的參數不同。這是我試圖調用的方法:我認爲你需要使用獲得MemberInfoIgnore方法.Ignore()

public void Ignore<TProperty>(
    Expression<Func<TStructuralType, TProperty>> propertyExpression 
) 

回答

1

MethodInfo ignoreMethod = typeof(StructuralTypeConfiguration<>) 
    .MakeGenericType(entityType) 
    .GetMethod("Ignore") 
    .MakeGenericMethod(propertyInfo.PropertyType); 

Ignore是對應於一個泛型參數的方法Expression的屬性類型,因此您需要在嘗試調用它之前提供屬性類型。

+0

完美工作調用爲:ignoreMethod.Invoke(entityConfiguration,new [] {propertyLambda});謝謝! – powlette 2013-02-13 00:40:01

相關問題