Ignoring all properties but some in Entity Framework 6

前端 未结 2 966
醉话见心
醉话见心 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<T> IgnoreAllBut<T>(this EntityTypeConfiguration<T> entityTypeConfiguration,
            params Expression<Func<T, object>>[] 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<Func<T, object>>(expression, param);
            entityTypeConfiguration.Ignore(result);
        }
        return entityTypeConfiguration;
    }
    
    0 讨论(0)
  • 2021-01-16 04:55

    You can mark individual properties as NotMapped within the class itself.

    public class MyPoco
    {
        public int Id { get; set; }
    
        [NotMapped]
        public string Name { get; set; }
    
        public int SomeSpecialId { get; set; }
    }
    

    Doesn't solve your issue of 'ignore everything but this' but might make it obvious what is and isn't included.

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