Ignoring all properties but some in Entity Framework 6

c# entity-framework entity-framework-6

Question

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 achieve this with the Fluent API by using the Ignore() method. But is there also the possibility of not only ignoring a defined property but all properties but the defined?
So if you have a POCO like this:

public class MyPoco
{
    public int Id { get; set; }
    public string Name { get; set; }
    .
    .
    .
    public int SomeSpecialId { get; set; }
}

And you only want to store the Id and the SomeSpecialId, you would do:

protected override void OnModelCreating(DbModelBuilder builder)
{
    builder.Entity<MyPoco>().Ignore(x => x.Name);
    builder.Entity<MyPoco>().Ignore(x => x.WhatEver);
    .
    .
    .
    // ignore everything but Id and SomeSpecialId
    base.OnModelCreating(builder);
}

Problem now is that if you have to extend the POCO but don't want to persist those extended properties you also have to change the OnModelCreating() method. So is there a way of doing something like:

public override void OnModelCreating(DbModelBuilder builder)
{
    builder.Entity<MyPoco>().IgnoreAllBut(x => x.Id, x.SomeSpecialId);
    base.OnModelCreating(builder);
}
1
1
6/26/2015 7:01:00 AM

Accepted Answer

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;
}
3
6/26/2015 8:03:20 AM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow