Use Entity Framework's StructuralTypeConfiguration.Ignore() to Ignore all properties but specified set

后端 未结 1 1786
旧巷少年郎
旧巷少年郎 2021-01-07 10:31

In EF CodeFirst Fluent API I can write something like this:

modelBuilder.Entity()
            .Ignore(e => e.Property1);
modelBuilder.Enti         


        
1条回答
  •  礼貌的吻别
    2021-01-07 11:07

    This is draft, but works:

    public static void IgnoreAllBut(
        this StructuralTypeConfiguration configuration,
        params Expression>[] 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 ConvertExpressionsToMembers(
        Expression>[] expressions)
    {
        var members = new List();
        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;
    }
    

    Thanks to DarkGray for code in linked question.

    0 讨论(0)
提交回复
热议问题