Bob5421
Bob5421

Reputation: 9073

Error in asp.net mvc core 2 scaffolding generated Controller

I am working on an ASP.Net Core 2 MVC Application.

I am generating one controller per table for my backoffice with this command:

dotnet aspnet-codegenerator --project . controller -name MYTABLEController -m MYTABLE -dc MYDBContext

(replace MYTABLE and MYDBContext are examples).

Here is what the csharp Controller looks like:

namespace MYPROJECT.Controllers
{
    public class MYTABLEController : Controller
    {
        private readonly MYDBContext _context;

        public ContactsController(MYDBContext context)
        {
            _context = context;
        }

Has you can see it creates a constructor which accepts one parameter: the database object (entityframework).

When i call the web page, i get an error on this context because it is not initialized.

Here what i have to do to make it work:

namespace MYPROJECT.Controllers
{
    public class MYTABLEController : Controller
    {
        private readonly MYDBContext _context = new MYDBContext();

        public ContactsController()
        {

        }

So my question are:

  1. Is there a best way to correct this problem ? I am wondering if it is really a bug or if i miss something.

  2. Look and feel of each generated chtml view is very ugly. Are there some options to get something more sexy ?

Thanks

Upvotes: 0

Views: 546

Answers (1)

Muqeet Khan
Muqeet Khan

Reputation: 2114

The generated controller code seems fine. You did not mention the exact error, but, I am assuming you are getting the error because you haven't added the MYDBContext in your services container.

In your startup.cs file you need to add this MYDBContext into the services container so that your controller will get it injected properly. Example,

    services.AddDbContext<MYDBContext>(options =>
        options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

After doing this, if you get the error as below:

System.ArgumentException: AddDbContext was called with configuration, but the context type 'MyDBContext' only declares a parameterless constructor.

then it means your scaffolded DbContext is not configured properly to be injected with the correct options parameter. Update the constructor to:

public partial class MYDBContext : DbContext
{
    public MYDBContext(DbContextOptions<MYDBContext> options)
        : base(options)
    {

    }

Upvotes: 1

Related Questions