我可以将 DbContext 作为接口或委托传递吗
我有两个 dbcontext 所以想通过一些函数传递它,这样我就可以在两个 dbcontext 之间切换,或者我必须更改所有 api 控制器
public class AccountClassesController : ControllerBase
{
private readonly ApplicationDbContext _context;
public AccountClassesController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/AccountClasses
[HttpGet]
public async Task<ActionResult<IEnumerable<AccountClass>>> GetAccountClass()
{
return await _context.AccountClass.ToListAsync();
}
不想从控制器调用 ApplicationDbContext 通过某些函数或
我拥有的 东西调用它现在为 postgresql 和 sqlserver 实现了数据库连接,每个人首先在代码中创建不同类型的迁移,因此必须创建两个 dbcontext,现在我希望当我使用 postgresql 或 时能够在 dbcontext 之间切换sql服务器
I am having two dbcontext so want to pass it though some function so I can switch between the two dbcontext or I have to change in all the api controller
public class AccountClassesController : ControllerBase
{
private readonly ApplicationDbContext _context;
public AccountClassesController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/AccountClasses
[HttpGet]
public async Task<ActionResult<IEnumerable<AccountClass>>> GetAccountClass()
{
return await _context.AccountClass.ToListAsync();
}
don't want to call the ApplicationDbContext from controller call it through some function or something
I have implemented database connection for postgresql and sqlserver now for them each one creates a different type of migration in code first, so had to create two dbcontext, now I want to be able to switch between dbcontext when I using postgresql or sql server
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您可以创建接口并修改您的应用程序DBContext以实现。
接口
注入DBContext实例铸件作为控制器中的接口:
必须配置依赖项注入框架以将新的应用程序dbcontext注入IACCONTCLASS。
Yes, you can create interfaces and modify your ApplicationDbContext to implement.
interface
Inject DbContext instance casting as interface in your controller:
You must configure you dependency injection framework to inject a new ApplicationDbContext as IAccountClass.
您可以在此处查看此答案将EF dbcontext作为服务的代表来附加所有更改是一个好习惯。
但是,如果您的应用程序没有任何性能问题,即使您实施了应有的新上下文EF是令人难以置信的快速管理和构建的。
You can check this answer here is it a good practice to pass an EF DbContext as delegate in services to attach all changes on it.
But if you application don't have any performance issues is fine even if you instance new context due EF is incredible fast managing and building it up.