PAYATHON 2026

如何在 Entity Framework Core 共用 DLL 中按需使用实体

排障赵师傅

结论

共享实体可以放在同一个 DLL 中,但每个 DbContext 都要有一套完整、自洽的 EF Core 模型。

如果某个应用不使用 EFRmaFollowUpEntity,应在该应用的 OnModelCreating 中排除以下内容:

  1. EFRmaFollowUpEntity 类型;
  2. EFPersonEntity、EFRmaEntity 中指向该类型的导航属性;
  3. 与该实体相关的 IEntityTypeConfiguration。

不声明 DbSet<EFRmaFollowUpEntity> 并不能把该实体排除在模型之外,因为 EF Core 还会通过导航属性发现实体类型。

推荐配置

假设当前应用使用 EFPersonEntity 和 EFRmaEntity,但不使用 EFRmaFollowUpEntity,可以这样配置:

public class dMBPDDbContext
    : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
    public DbSet<EFPersonEntity> People { get; set; } = null!;
    public DbSet<EFRmaEntity> Rmas { get; set; } = null!;

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.ApplyConfiguration(new PersonEntityConfiguration());
        builder.ApplyConfiguration(new RmaEntityConfiguration());

        builder.Ignore<EFRmaFollowUpEntity>();

        builder.Entity<EFPersonEntity>()
            .Ignore(p => p.RmaFollowUpCommentByCollection);

        builder.Entity<EFRmaEntity>()
            .Ignore(r => r.RmaFollowUpCollection);
    }
}

其中,RmaFollowUpCollection 要替换成 EFRmaEntity 中实际定义的属性名。

如果当前应用也不使用 EFRmaEntity,就不要调用 Entity<EFRmaEntity>(),否则这个调用会把该实体加入模型:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.ApplyConfiguration(new PersonEntityConfiguration());

    builder.Ignore<EFRmaEntity>();
    builder.Ignore<EFRmaFollowUpEntity>();

    builder.Entity<EFPersonEntity>()
        .Ignore(p => p.RmaFollowUpCommentByCollection);
}

为什么没有 DbSet 仍会报错

DbSet<TEntity> 只是 EF Core 发现实体的入口之一。实体还可能通过以下方式进入模型:

  • ModelBuilder.Entity<TEntity>()
  • ApplyConfiguration(new SomeEntityConfiguration())
  • ApplyConfigurationsFromAssembly(...)
  • 其他实体上的导航属性
  • 已配置关系中引用的实体类型

例如,EFPersonEntity 中有下面这个属性:

public ICollection<EFRmaFollowUpEntity>?
    RmaFollowUpCommentByCollection { get; set; }

EF Core 会将它识别为集合导航,并尝试把 EFRmaFollowUpEntity 加入模型。如果关系的另一端不完整,或者没有应用相应的关系配置,模型验证阶段就可能出现以下错误:

Unable to determine the relationship represented by navigation ...

所以,没有声明 DbSet,不代表实体没有进入 EF Core 模型。

不要加载未使用实体的配置

当前应用不使用 follow-up 功能时,不要执行:

builder.ApplyConfiguration(
    new RmaFollowUpEntityConfiguration());

这段配置会直接引入 EFRmaFollowUpEntity,还会通过下面的关系继续引入 EFPersonEntity 等类型:

entity.HasOne(c => c.CommentBy)
    .WithMany(c => c.RmaFollowUpCommentByCollection)
    .HasForeignKey(c => c.CommentById)
    .OnDelete(DeleteBehavior.NoAction);

使用程序集扫描时也要留意下面的写法:

builder.ApplyConfigurationsFromAssembly(
    typeof(PersonEntityConfiguration).Assembly);

它可能会把 DLL 中所有 IEntityTypeConfiguration<T> 应用到当前模型。如果共享 DLL 中包含可选实体,可以显式加载当前应用需要的配置,也可以使用扫描方法提供的筛选条件:

builder.ApplyConfigurationsFromAssembly(
    typeof(PersonEntityConfiguration).Assembly,
    type => type == typeof(PersonEntityConfiguration)
         || type == typeof(RmaEntityConfiguration));

配置较多时,还可以在 common DLL 中提供按功能分组的扩展方法:

public static class CommonEntityModelBuilderExtensions
{
    public static ModelBuilder AddPersonModel(
        this ModelBuilder builder)
    {
        builder.ApplyConfiguration(
            new PersonEntityConfiguration());

        return builder;
    }

    public static ModelBuilder AddRmaModel(
        this ModelBuilder builder,
        bool includeFollowUps)
    {
        builder.ApplyConfiguration(
            new RmaEntityConfiguration());

        if (includeFollowUps)
        {
            builder.ApplyConfiguration(
                new RmaFollowUpEntityConfiguration());
        }
        else
        {
            builder.Ignore<EFRmaFollowUpEntity>();

            builder.Entity<EFPersonEntity>()
                .Ignore(p => p.RmaFollowUpCommentByCollection);

            builder.Entity<EFRmaEntity>()
                .Ignore(r => r.RmaFollowUpCollection);
        }

        return builder;
    }
}

应用侧只需选择要使用的模型:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.AddPersonModel();
    builder.AddRmaModel(includeFollowUps: false);
}

是否应该使用 [NotMapped]

也可以在导航属性上添加 [NotMapped]:

[NotMapped]
public ICollection<EFRmaFollowUpEntity>?
    RmaFollowUpCommentByCollection { get; set; }

不过,这会影响所有使用该实体类的 DbContext。其他需要 follow-up 关系的应用还要重新显式配置这个导航属性,因此不适合部分应用使用、部分应用不使用的情况。

这类需求更适合通过各个 DbContext 自己的 Fluent API 处理:

builder.Entity<EFPersonEntity>()
    .Ignore(p => p.RmaFollowUpCommentByCollection);

模型设计上的注意事项

实体 CLR 类型可以放在共享 DLL 中,但它进入某个 DbContext 后,具体映射应由该 DbContext 决定。共享实体不要求每个应用使用完全相同的 EF Core 模型。

如果不同应用的数据库结构差异较大,可以进一步拆分配置:

Common.Entities
Common.Persistence.Person
Common.Persistence.Rma
Common.Persistence.RmaFollowUp

实体类仍然可以共享,关系配置则按功能模块组织。这样能避免应用因加载整套配置,意外创建不需要的表、外键和迁移。

同一个 DbContext 类型也不宜根据普通运行时条件随意改变模型,因为 EF Core 会缓存模型。如果确实需要两套不同的模型,使用不同的 DbContext 类型通常更简单,各自的 migration 也更容易维护。

针对当前问题,不要应用 RmaFollowUpEntityConfiguration,并使用 Ignore<TEntity>() 和 Entity<TEntity>().Ignore(...) 排除未使用的实体及其导航属性。然后再执行 add-migration,EF Core 会根据当前应用实际纳入的实体生成模型。

备注:内容仅供参考。