Reputation: 3122
EF Core 2.2
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)?
Upvotes: 4
Views: 18276
Reputation: 2287
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);
}
}
Upvotes: 4
Reputation: 205619
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);
}
Upvotes: 7
Reputation: 1
You can use the NotMapped
attribute on such properties in the model class.
Or you can ignore the properties using reflection in DBContext class's OnModelCreating
method like below.
foreach(var property in typeof(INotPersistingProperties).GetProperties())
modelBuilder.Types().Configure(m => m.Ignore(property.Name));
Upvotes: 2
Reputation: 7204
You can put NotMapped
on the properties in the interface and then use MetadataType attribute
public interface INotPersistingProperties
{
[NotMapped]
string MyNotPersistingPropertyA { get; set; }
[NotMapped]
string MyNotPersistingPropertyB { get; set; }
}
[MetadataType(typeof(INotPersistingProperties))]
public class MyEntity : INotPersistingProperties
{
public int Id { get; set; }
public string MyNotPersistingPropertyA { get; set; }
public string MyNotPersistingPropertyB { get; set; }
}
or you can create a base class and put attribute NotMapped
on your properties
Upvotes: 6