IT Eng - BU
IT Eng - BU

Reputation: 79

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

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?

Upvotes: 2

Views: 669

Answers (1)

SpruceMoose
SpruceMoose

Reputation: 10320

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

Upvotes: 1

Related Questions