How to exclude a property of all entity types in EF Core configuration?

Viewed 379

All of my models have a dynamic property called RelatedItems. I want to dynamically ignore these properties for all entity types.

Thus I created a base DatabaseContext to centralize this convention.

public abstract DatabaseContext : DbContext
{

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var allEntities = modelBuilder.Model.GetEntityTypes();

            foreach (var entity in allEntities)
            {
                entity.Ignore("RelatedItems");
            }
        }
}

But this gives me this error:

DatabaseContext.cs(23,24): error CS1061: 'IMutableEntityType' does not contain a
definition for 'Ignore' and no accessible extension method 'Ignore' accepting a first
argument of type 'IMutableEntityType' could be found

How can I ignore a property on all of my models?

1 Answers
// Get all entities and filter the ones who has the RelatedItems properties
// This filter is not required, but for safety purpose I recomend to use it
// otherwise you could end up getting some weird errors during migration scaffolding
// In my case, without it, the scaffold command alarmed about an Enum that is not even related
var allEntities = modelBuilder.Model.GetEntityTypes()
                                            .Where(x => x.GetProperties().Count(x => x.Name == "RelatedItems") > 0);


foreach (var entity in allEntities)
{
    // Ignore property
    modelBuilder.Entity(entity.Name).Ignore("RelatedItems");
}
Related