实体框架核心模型在单独的插件程序集中

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

我正在开发一个在许多Web应用程序之间共享/重用的在线商店模块(类库)。我希望这个模块在独立的库中。

实现通用数据模型的最佳实践是什么:产品,订单等。我想将这些实体注入这些Web应用程序的现有Db上下文中。

我应该实现基本数据库上下文还是使用一些扩展方法,服务或中间件?

asp.net .net entity-framework-core
1个回答
1
投票

您可以尝试为实现IEntityTypeConfiguration的模型添加配置类,即。

public abstract class DbEntityConfig<T> : IEntityTypeConfiguration<T> where T: class, IDbEntity
{
    public virtual void Configure(EntityTypeBuilder<T> builder)
    {
        builder.HasKey(entity => entity.Id);
        builder.HasQueryFilter(entity => !entity.IsDeleted);
    }
}

 public class DummyEntityConfiguration: DbEntityConfig<Dummy>
     {
         public override void Configure(EntityTypeBuilder<Analysis> builder)
         {
            //Fluent Configuration here, especially table name
         }
     }

然后在DbContext OnModelCreating中:

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

            builder.ApplyConfiguration(new DummyEntityConfiguration());
}

这会将模型添加到DbContext中。然后,您可以尝试通过反射为每种类型导出DbEntityConfig应用配置。

可以通过DbContext.Set<T>访问模型只有这个解决方案的缺点是没有在配置中指定ToTable,表的名称将完全作为模型名称(因此没有自动复数),因为EF核心使用DbSet <> name作为表的名称,如果它不是可用的实体名称。

© www.soinside.com 2019 - 2024. All rights reserved.