Entity framework core 在AddDbContext之后,现在我想使用我的上下文
我决定使用这个AddDbContext方法为我的EntityFramework核心项目添加和设置上下文Entity framework core 在AddDbContext之后,现在我想使用我的上下文,entity-framework-core,Entity Framework Core,我决定使用这个AddDbContext方法为我的EntityFramework核心项目添加和设置上下文 services.AddDbContext<ExampleContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ExampleConnection"))); // https://stackoverflow.com/a/51970589/196526 我假设这个AddDbCo
services.AddDbContext<ExampleContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ExampleConnection")));
// https://stackoverflow.com/a/51970589/196526
我假设这个AddDbContext允许我们添加一个全局上下文,并且在我的控制器或服务类中需要时可以稍后检索它。如何使用它?好吧,dotnetcore现在已经内置了依赖注入。在控制器、服务或存储库类中使用它的方式与构造函数注入一样简单 示例-
public class AccountRepository : IAccountRepository{
private readonly DbContext _exampleContext;
public AccountRepository(ExampleContext context){
_exampleContext = context;
}
}您还可以使用IServiceProvider.GetService从服务提供商处检索它