ASP.Net Core 2 - Using a DBContext having defaultConnectionString from appsettings

asp.net-core-2.0 asp.net-core-mvc entity-framework entity-framework-core

Question

I want to create a basic CRUD in ASP.Net Core 2 with EntityFrameworkCore.

My appsettings.json file is like this-

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

I want to read connection from this file. What I have done is - In Startup.cs - Startup

        //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();

and then in ConfigureServices-

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

Then in controller, I am trying this-

enter image description here

So, I am getting this error-

enter image description here

What do I need to do to solve this error?

Can anyone please help?

1
2
1/16/2018 7:25:06 AM

Accepted Answer

You need to allow your DbContext to be injected into your controller as follows:

public class YourController
{
    InventoryManagementDbContext _context;

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

    public Action Index()
    {
        _context.Employee.Add(...);
        await _context.SaveChangesAsync();
        return View();
    }
}
1
1/16/2018 9:25:59 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow