EF Core在上下文中的初始化配置
public ABCDataContext(DbContextOptions<GoldenDataContext> options) : base(options)
{
}
这样做的目的是让它方便自动依赖注入 Startup文件中配置如下:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
var dbconfig = Configuration.BindConfig<DMDbConfiguration>();
services
.AddDbContext<ABCDataContext>(options =>
{
options.UseSqlServer(dbconfig.ABCDataConnectionString);
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
})
// mvc 全局设置
AddMvc(services);
// 实例化autofac 注册容器
AddContainerBuilder(services);
return new AutofacServiceProvider(ApplicationContainer);
}
这时 在程序中使用自动依赖注入数据库上下文对象:
public class WorkorderBillService
{
private readonly ABCRawDataContext abcDataContext;
public WorkorderBillService(ABCDataContext abcDataContext)
{
this.abcDataContext = abcDataContext;
}
}
但是如果要在程序中自己创建数据库上下文对象:
var optionsBuilder = new DbContextOptionsBuilder<ABCDataContext>();
optionsBuilder.UseSqlServer(configuration.ABCDataConfiguration);
using (ABCDataContext abcDataContext = new
ABCDataContext(optionsBuilder.Options))
{
//.........
}