Ignoring all properties but some in Entity Framework 6

前端 未结 2 999
醉话见心
醉话见心 2021-01-16 04:07

I want to persist some data on a database using Entity Framework.
I have some bigger POCOs but I want to store some of the properties only.

I know that I can a

2条回答
  •  青春惊慌失措
    2021-01-16 04:34

    You can write an extension method that will do that. The code is not simple because you need to work with expression trees.

    Here is your IgnoreAllBut method:

    public static EntityTypeConfiguration IgnoreAllBut(this EntityTypeConfiguration entityTypeConfiguration,
            params Expression>[] properties) where T : class
    {
        // Extract the names from the expressions
        var namesToKeep = properties.Select(a =>
        {
            var member = a.Body as MemberExpression;
            // If the property is a value type, there will be an extra "Convert()"
            // This will get rid of it.
            if (member == null)
            {
                var convert = a.Body as UnaryExpression;
                if (convert == null) throw new ArgumentException("Invalid expression");
                member = convert.Operand as MemberExpression;
            }
            if (member == null) throw new ArgumentException("Invalid expression");
            return (member.Member as PropertyInfo).Name;
        });
        // Now we loop over all properties, excluding the ones we want to keep
        foreach (var property in typeof(T).GetProperties().Where(p => !namesToKeep.Contains(p.Name)))
        {
            // Here is the tricky part: we need to build an expression tree
            // to pass to Ignore()
            // first, the parameter
            var param = Expression.Parameter(typeof (T), "e");
            // then the property access
            Expression expression = Expression.Property(param, property);
            // If the property is a value type, we need an explicit Convert() operation
            if (property.PropertyType.IsValueType)
            {
                expression = Expression.Convert(expression, typeof (object));
            }
            // last step, assembling everything inside a lambda that
            // can be passed to Ignore()
            var result = Expression.Lambda>(expression, param);
            entityTypeConfiguration.Ignore(result);
        }
        return entityTypeConfiguration;
    }
    

提交回复
热议问题