2

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 Answer 1

1

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();
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

how can I call ensureCreated in there? Can you please help?
This post might be useful: stackoverflow.com/questions/36958318/…
Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.