EF Core 2.1.1 how to ignore some properties when entity implements some specific interface

.net c# entity-framework-core


Having this interface:

public interface INotPersistingProperties
   string MyNotPersistingPropertyA { get; set; }
   string MyNotPersistingPropertyB  { get; set; }

and a lot of entities that implements the interface

public class MyEntity : INotPersistingProperties
  public int Id { get; set; }
  public string MyNotPersistingPropertyA { get; set; }
  public string MyNotPersistingPropertyB { get; set; }

is there any chance to automatically ignore, for all entities that implement the INotPersistingProperties, those properties (using Fluent API)?

9/24/2018 8:45:37 PM

Accepted Answer

Currently EF Core does not provide a way to define custom conventions, but you can add the following to your OnModelCreating override (after all entity types are discovered) to iterate all entity types implementing the interface and call Ignore fluent API for each property:

var propertyNames = typeof(INotPersistingProperties).GetProperties()
    .Select(p => p.Name)
var entityTypes = modelBuilder.Model.GetEntityTypes()
    .Where(t => typeof(INotPersistingProperties).IsAssignableFrom(t.ClrType));
foreach (var entityType in entityTypes)
    var entityTypeBuilder = modelBuilder.Entity(entityType.ClrType);
    foreach (var propertyName in propertyNames)
9/24/2018 9:40:26 AM

Popular Answer

To ignore all classes of specific interface for EF Core I used this code:

protected override void OnModelCreating(ModelBuilder builder)

         var multitenantTypes = typeof(IMultiTenantEntity)
            .Where(x => typeof(IMultiTenantEntity).IsAssignableFrom(x))

        foreach (var typeToIgnore in multitenantTypes)


Related Questions


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