我制作了一个"背景"类称为" ApplicationDbContext"它通过构造获取配置所需的信息:
namespace SportsStore.Models
{
public class ApplicationDbContext:DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext>
options) : base(options) { }
public DbSet<Product> Products { get; set; }
}
}
然后我在启动类中注册了这个上下文类,使用AddDbContext方法连接到我的数据库:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public Startup(IConfiguration configuration) => Configuration = configuration;
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(
options =>options.UseSqlServer(Configuration["Data:SportStoreProducts:ConnectionStrings"]));
services.AddTransient<IProductRepository, EFProductRepository>();
services.AddMvc();
}
最后,创建了一个名为seedata的类来使用&#34; ApplicationDbContext&#34;已配置为将我的模型对象保存在数据库中的类:
public class SeedData
{
public static void EnsurePopulated(IApplicationBuilder app)
{
ApplicationDbContext context =
app.ApplicationServices.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
现在我的问题是我们如何配置构造,以便代替访问已配置的ApplicationDbContext对象(通过访问IserviceProvider)
ApplicationDbContext context =
app.ApplicationServices.GetRequiredService<ApplicationDbContext>();
我们如何通过构造得到ApplicationDbContext(here:context)的实例,如:
ApplicationDbContext context=new ApplicationDbContext();
我应该在构造参数内放置与上面代码相同的结果?在任何情况下,我是否需要100%注册上下文类&#34; ApplicationDbContext&#34;?
答案 0 :(得分:1)
您可以添加空构造函数和override OnConfiguring
方法:
public class ApplicationDbContext : DbContext
{
//another code...
public ApplicationDbContext()
{}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
optionsBuilder.UseSqlServer(_connectionString);
}
}