Entity Framework Core - migration creates all properties from model instead of desired ones

249 views Asked by At

these are my beginnings with EfCore (earlier I was in nHibernate and Dapper). I have a problem with mappings.

My model looks like that:

public class Document
{
   public Guid Id {get;set;}
   public string Name {get;set;}

   public int ValueIDontWantToBeInDb {get; set;}
}

My mappings:

b.ToTable("documents");
b.Property(x => x.Id).ValueGeneratedOnAdd();
b.HasKey(x => x.Id);
b.Property(x => x.Name).IsRequired();

(where b is EntityTypeBuilder received in IEntityTypeConfiguration implementation.

As you can see, I never use ValueIDontWantToBeInDb, but EfCore keeps adding this to table schema. Why is it so and what to do to make it add only those properties that I want?

I know there is a Ignore method. But then I would have to call it on every model on every property that I do not want to be added to schema.

I just want to show to EfCore - "Hey, map these properties like so" - just like in nHibernate. How to do this?

1

There are 1 answers

0
Adam Jachocki On

Ok, I create some solution for this. But I think that it's really outreagous that EfCore doesn't have such a solution in standard. So, first create base class for all your mappings. This is really the place with all the magic:

abstract class BaseMap<T>: IEntityTypeConfiguration<T> where T: class, IDbItem //IDbItem is my own constraint, just an interface that has Id property
{
    EntityTypeBuilder<T> theBuilder;
    List<string> mappedPropertyNames = new List<string>();

    protected PropertyBuilder<TProperty> Map<TProperty>(Expression<Func<T, TProperty>> x) //this will be called instead of Property()
    {
        mappedPropertyNames.Add(GetPropertyName(x)); 
        return theBuilder.Property(x);
    }

    protected ReferenceNavigationBuilder<T, TRelatedEntity> HasOne<TRelatedEntity>(Expression<Func<T, TRelatedEntity>> x)
        where TRelatedEntity: class
    {
        mappedPropertyNames.Add(GetPropertyName(x));
        return theBuilder.HasOne(x);
    }

    protected CollectionNavigationBuilder<T, TRelatedEntity> HasMany<TRelatedEntity>(Expression<Func<T, IEnumerable<TRelatedEntity>>> x)
        where TRelatedEntity: class
    {
        mappedPropertyNames.Add(GetPropertyName(x));
        return theBuilder.HasMany(x);
    }

    protected PropertyBuilder<TColumnType> Map<TColumnType>(string propName)
    {
        mappedPropertyNames.Add(propName);
        return theBuilder.Property<TColumnType>(propName);
    }

    protected abstract void CreateModel(EntityTypeBuilder<T> builder);

    public void Configure(EntityTypeBuilder<T> builder)
    {
        theBuilder = builder;

        Map(x => x.Id).ValueGeneratedOnAdd();
        builder.HasKey(x => x.Id);

        CreateModel(builder);

        IgnoreUnmappedProperties(builder);

    }

    void IgnoreUnmappedProperties(EntityTypeBuilder<T> builder)
    {
        PropertyInfo[] propsInModel = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
        foreach (var prop in propsInModel)
        {
            if (!mappedPropertyNames.Contains(prop.Name))
            {
                builder.Ignore(prop.Name);
            }
        }
    }

    string GetPropertyName<TProperty>(Expression<Func<T, TProperty>> memberExpression)
    {
        MemberExpression member = null;

        switch (memberExpression.Body)
        {
            case UnaryExpression ue when ue.Operand is MemberExpression:
                member = ue.Operand as MemberExpression;
                break;

            case MemberExpression me:
                member = me;
                break;

            default:
                throw new InvalidOperationException("You should pass property to the method, for example: x => x.MyProperty");

        }

        var pInfo = member.Member as PropertyInfo;
        if (pInfo == null)
            throw new InvalidOperationException("You should pass property to the method, for example: x => x.MyProperty");

        return pInfo.Name;
    }
}

Now example of a class that derives from this and creates real object map:

class DocumentMap : BaseMap<Document>
{
    protected override void CreateModel(EntityTypeBuilder<Document> b)
    {
        b.ToTable("documents");

        Map(x => x.Name).IsRequired();
        Map<Guid>("Owner_id").IsRequired();

        HasOne(x => x.Owner)
            .WithMany()
            .HasForeignKey("Owner_id")
            .HasConstraintName("FK_Users_Documents")
            .IsRequired()
            .OnDelete(DeleteBehavior.Cascade);

        HasMany(x => x.Periods)
            .WithOne(y => y.ParentDocument);

        HasMany(x => x.Loans)
            .WithOne(y => y.ParentDocument);
    }
}

Notice that instead of using methods from EntityTypeBuilder, I use methods derived from base class. Frankly speaking I even don't have to pass EntityTypeBuilder object here.

And all is called in DbContext like this:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
    }