【问题标题】:ASP.Net Core 2 - Using a DBContext having defaultConnectionString from appsettingsASP.Net Core 2 - 使用具有来自 appsettings 的 defaultConnectionString 的 DBContext
【发布时间】:2018-01-16 07:25:06
【问题描述】:

我想用 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")));

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

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

我需要做什么来解决这个错误?

有人可以帮忙吗?

【问题讨论】:

    标签: entity-framework asp.net-core-mvc entity-framework-core asp.net-core-2.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();
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多