使用Entity Framework的StructuralTypeConfiguration.Ignore()忽略除指定集之外的所有属性

时间:2012-03-06 14:09:21

标签: c# .net linq entity-framework ef-code-first

在EF CodeFirst Fluent API中,我可以这样写:

modelBuilder.Entity<MyEntity>()
            .Ignore(e => e.Property1);
modelBuilder.Entity<MyEntity>()
            .Ignore(e => e.Property2);

如何忽略所有属性,只需要一小部分,如下:

modelBuilder.Entity<MyEntity>()
            .IgnoreAllBut(e => e.ID, e => e.Important);

是否可以编写像IgnoreAllBut这样的扩展方法?

1 个答案:

答案 0 :(得分:3)

这是草稿,但有效:

public static void IgnoreAllBut<TStructuralType>(
    this StructuralTypeConfiguration<TStructuralType> configuration,
    params Expression<Func<TStructuralType, object>>[] includes)
    where TStructuralType : class
{
    var includeMembers = ConvertExpressionsToMembers(includes);
    var type = typeof(TStructuralType);
    var properties = type.GetProperties();
    var typeParameter = Expression.Parameter(type);
    var configurationType = configuration.GetType();
    var ignoreMethod = configurationType.GetMethod("Ignore");
    foreach (var property in properties)
    {
        if (!includeMembers.Any(member => member.Name == property.Name))
        {
            var propertyExpression = Expression.Property(typeParameter, property);
            var lambdaExpression = Expression.Lambda(propertyExpression, typeParameter);
            var genericIgnoreMethod = ignoreMethod.MakeGenericMethod(property.PropertyType);
            var parameters = new object[] { lambdaExpression };
            genericIgnoreMethod.Invoke(configuration, parameters);
        }
    }
}

private static List<MemberInfo> ConvertExpressionsToMembers<TStructuralType>(
    Expression<Func<TStructuralType, object>>[] expressions)
{
    var members = new List<MemberInfo>();
    foreach (var lambda in expressions)
    {
        var expression = lambda.Body;
        var memberExpression = expression as MemberExpression;
        if (memberExpression == null)
        {
            var unaryExpression = expression as UnaryExpression;
            memberExpression = unaryExpression.Operand as MemberExpression;
        }
        members.Add(memberExpression.Member);
    }
    return members;
}

感谢DarkGray提供链接question中的代码。