ApplyConfigurationsFromAssembly with Filter Entityframework Core

问题描述 投票:0回答:1

我需要使用特定类型的实体创建数据库上下文,因为我在解决方案上具有多个Db上下文。我的问题是OnModelCreating我们从程序集builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly())应用配置,所以我只想应用IEntityTypeConfiguration的配置,带有实体的类型具有基本模型BaseEntity,如下所示

public class DaysOfWeekBuilder : IEntityTypeConfiguration<DaysOfWeek>
{
    public void Configure(EntityTypeBuilder<DaysOfWeek> builder)
    {
        builder.ToTable("DaysOfWeek");
        builder.Property(e => e.Name).HasMaxLength(15);
    }
}

所以DaysOfWeek实体具有基类BaseEntity

public class DaysOfWeek : BaseEntity
{
    public string Name { get; set; }
}

如何使用具有基本模型IEntityTypeConfiguration的实体过滤BaseEntity

谢谢

c# asp.net-core entity-framework-core ef-migrations dbcontext
1个回答
0
投票

documentation说您可以添加一个谓词作为第二个参数进行过滤。

在这种情况下,谓词将扫描类型,并针对每种类型,将检查其是否实现了IEntityTypeConfiguration<T>接口,以及T是否继承了BaseEntity

builder.ApplyConfigurationsFromAssembly(
    Assembly.GetExecutingAssembly(), 
    t => t.GetInterfaces().Any(i => 
                i.IsGenericType &&
                i.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>) &&
                typeof(BaseEntity).IsAssignableFrom(i.GenericTypeArguments[0]))
);
© www.soinside.com 2019 - 2024. All rights reserved.