① 将上一篇的Models/UserContext.cs文件中的用来指定使用的数据库逻辑的OnConfiguring方法删除,将逻辑移到Startup.cs文件中的ConfigureServices方法中。

public void ConfigureServices(IServiceCollection services){    string connectionString = Configuration.GetConnectionString("MyConnection");

    services.AddDbContext<UserContext>(options =>
                options.UseMySQL(connectionString));    // Add framework services.
    services.AddMvc();
}

② 在UserController.cs 构造函数中采用依赖注入来注入一个数据库上下文到该控制器。数据库上下文将被应用到控制器中的每一个CRUD方法。

private readonly UserContext _context;public&n
        
		

网友评论