ASP.Net Core 2 - 使用来自appsettings的具有defaultConnectionString的DBContext

时间:2018-01-16 07:25:06

标签: entity-framework asp.net-core-mvc entity-framework-core asp.net-core-2.0

我想在带有EntityFrameworkCore的ASP.Net Core 2中创建一个基本的CRUD。

我的 appsettings.json 文件就像这样 -

"DefaultConnection": "server=localhost; port=3306; database=inventory_management; user=root; password=;"

我想从此文件中读取连接。我所做的是 - 在 Startup.cs - 启动

        //Configuration = configuration;
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();

然后在ConfigureServices中

services.AddDbContext<InventoryManagementDbContext>(options => options.UseMySQL(Configuration.GetConnectionString("DevelopConnection")));

然后在控制器中,我正在尝试这个 -

enter image description here

所以,我收到了这个错误 -

enter image description here

我需要做些什么才能解决此错误?

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您需要按照以下方式将DbContext注入控制器:

public class YourController
{
    InventoryManagementDbContext _context;

    // Dependency Injection
    public YourController(InventoryManagementDbContext context)
    {
        _context = context;
    }

    public Action Index()
    {
        _context.Employee.Add(...);
        await _context.SaveChangesAsync();
        return View();
    }
}