我在这里找到了答案:
GetEntityTypes: configure entity properties using the generic version of .Property<TEntity> in EF Core
除了上面的注释之外,还有一种方法可以做到这一点,而不必为每个实体调用它。这可能会被重构成一些扩展方法,正如Erndob在我的问题下的评论所提到的。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
if (typeof(ISoftDeletable).IsAssignableFrom(entityType.ClrType))
{
modelBuilder.Entity(entityType.ClrType).Property<bool>(nameof(ISoftDeletable.IsActive)).HasDefaultValue(true);
}
}
}
解决办法是
ModelBuilder.Model.GetEntityTypes()
并查找可从
ISoftDeletable
.
在我看来,这比手动配置它,甚至创建一个抽象的
IEntityTypeConfiguration<>
上课,因为你不必记得把它全部用上
等位异构体
上课。
更干净:
public static class ModelBuilderExtensions
{
public static ModelBuilder EntitiesOfType<T>(this ModelBuilder modelBuilder,
Action<EntityTypeBuilder> buildAction) where T : class
{
return modelBuilder.EntitiesOfType(typeof(T), buildAction);
}
public static ModelBuilder EntitiesOfType(this ModelBuilder modelBuilder, Type type,
Action<EntityTypeBuilder> buildAction)
{
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
if (type.IsAssignableFrom(entityType.ClrType))
buildAction(modelBuilder.Entity(entityType.ClrType));
return modelBuilder;
}
}
以及
OnModelCreating
:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.EntitiesOfType<ISoftDeletable>(builder =>
{
builder.Property<bool>(nameof(ISoftDeletable.IsActive)).HasDefaultValue(true);
// query filters :)
var param = Expression.Parameter(builder.Metadata.ClrType, "p");
var body = Expression.Equal(Expression.Property(param, nameof(ISoftDeletable.IsActive)), Expression.Constant(true));
builder.HasQueryFilter(Expression.Lambda(body, param));
});
}