EF 6动态模型配置

时间:2016-05-26 11:37:40

标签: c# entity-framework ef-code-first

我使用自定义验证属性而不是内置的DataAnnotation属性。在DbContext中,我使用反射运行实体,并根据这些属性配置模型。不幸的是,以下代码不适用于整数属性。这可能是因为它找不到合适的过载物品"物业"方法

/// <summary>
/// This method should return the 
/// property configuration object of the modelbuilder
/// mb.Entity<User>().Property(p=>p.Age)
/// </summary>
private PrimitivePropertyConfiguration GetStringPropertyConfiguration(DbModelBuilder mb, Type entityType, string propertyName)
{
    //mb.Entity<User>()
    var structuralConfiguration = typeof(DbModelBuilder).GetMethod("Entity").MakeGenericMethod(entityType).Invoke(mb, null);
    //p=>p.Age
    var param = Expression.Parameter(entityType);
    var propertyExpression = Expression.Lambda(Expression.Property(param, propertyName), param);
    //.Property()
    var propertyMethod = structuralConfiguration.GetType().GetMethod("Property", new[] { propertyExpression.GetType() });

    if (propertyMethod != null)
    {
        var stringpropertyConfiguration =
            propertyMethod.Invoke(structuralConfiguration, new[] {propertyExpression}) as
                PrimitivePropertyConfiguration;
        return stringpropertyConfiguration;

    }
    else
    {
        throw new Exception("This should not happen");
    }
}

//来测试

public class Entity
{
    public string StringProperty { get; set; }
    public int IntegerProperty { get; set; }
}

var stringPropertyConfig = GetStringPropertyConfiguration(mb, typeof (Entity), "StringProperty");
var intPropertyConfig = GetStringPropertyConfiguration(mb, typeof(Entity), "IntegerProperty");

1 个答案:

答案 0 :(得分:0)

您需要对您的财产归还类型强烈输入int

这样的东西适用于private PrimitivePropertyConfiguration GetStructPropertyConfiguration(DbModelBuilder mb, Type entityType, string propertyName, Type propertyType) { var structuralConfiguration = typeof(DbModelBuilder).GetMethod("Entity") .MakeGenericMethod(entityType).Invoke(mb, null); var param = System.Linq.Expressions.Expression.Parameter(entityType); var funcType = typeof(Func<,>).MakeGenericType(entityType, propertyType); var expressionType = typeof(System.Linq.Expressions.Expression); var lambdaMethod = expressionType.GetMethods(BindingFlags.Static | BindingFlags.Public) .Where(mi => mi.Name == "Lambda").FirstOrDefault(); var genericLambdaMethod = lambdaMethod.MakeGenericMethod(funcType); var prop = System.Linq.Expressions.Expression.Property(param, propertyName); var inv = genericLambdaMethod.Invoke(null, new object[] { prop, new[] { param } }); var propertyMethod = this.GetType().GetMethods(BindingFlags.Public|BindingFlags.Instance) .Where(mi => mi.Name == "Property").FirstOrDefault(); var propertyMethodGeneric = propertyMethod.MakeGenericMethod(propertyType); var mapping = propertyMethodGeneric.Invoke(structuralConfiguration , new[]{inv}) as PrimitivePropertyConfiguration; return mapping; } 类型的属性:

stop