Reputation: 79
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-
So, I am getting this error-
What do I need to do to solve this error?
Can anyone please help?
Upvotes: 2
Views: 669
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