【发布时间】:2021-12-04 15:28:26
【问题描述】:
我正在编写一个库,它将围绕 Entity Framework Core 5+ 中的 DbContext 类提供新的 API。我已经有了这些新 API 的一个版本,但它需要手动干预最终的 DbContext 实现,例如:
// Code in the library.
public static class AwesomeExtensions
{
public static ModelBuilder AddAwesomeExtensionsSupportingEntities(this ModelBuilder modelBuilder)
{
// Set up custom entities I need to make this work.
return modelBuilder;
}
}
// Code somewhere else.
public class MyBusinessDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// I would like to avoid doing this here.
modelBuilder.AddAwesomeExtensionsSupportingEntities();
// Business as usual (database entities).
}
}
经过扩展搜索后,我没有在 EF Core API 中找到允许我以非侵入方式执行此操作的扩展点。
这是我目前发现的:
- CustomDbContext 类:我可以从
DbContext继承并覆盖OnModelCreating方法,但这并不比我现在所做的更好。 -
DbContextOptionsBuilder.UseModel:我认为这可能是我可以使用但增加了太多复杂性的东西。通过使用此 API,框架将不会调用OnModelCreating方法。 -
IEntityTypeConfiguration<TEntity>:我支持这个,但它还要求你可以访问ModelBuilder实例,然后你可以使用ModelBuilder.ApplyConfigurationsFromAssembly方法。
理想情况下,我想通过注册DbContext 依赖项时提供的DbContextOptionsBuilder 对象来执行此操作,例如:
// Code in some application.
public void AddServices(IServiceCollection services)
{
services.AddDbContext<MyBusinessDbContext>(options =>
{
// The ideal solution.
options.UseAwesomeExtensions();
});
}
如果我只能在ModelBuilder 的实例被提供给OnModelCreating 方法之前以不需要修改DbContext 实现的方式截取它,那将对我有所帮助。
欢迎提出任何想法。
谢谢。
【问题讨论】:
标签: c# entity-framework .net-core entity-framework-core