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)?
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)
.ToList();
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)
entityTypeBuilder.Ignore(propertyName);
}
To ignore all classes of specific interface for EF Core I used this code:
protected override void OnModelCreating(ModelBuilder builder)
{
var multitenantTypes = typeof(IMultiTenantEntity)
.Assembly
.GetTypes()
.Where(x => typeof(IMultiTenantEntity).IsAssignableFrom(x))
.ToArray();
foreach (var typeToIgnore in multitenantTypes)
{
builder.Ignore(typeToIgnore);
}
}