2

At the point of creating a new MVC Controller:

enter image description here

after I click Add button, I get the following Error:

enter image description here

Here is my simple Context class:

  public class MainDbContext : DbContext
  {
    public MainDbContext(DbContextOptions<MainDbContext> options) : base(options)
    {
    }

    public DbSet<Todo> Todo { get; set; }

  }

and my simple model:

public partial class Todo
{
    public int Id { get; set; }
    public string TaskName { get; set; }
}

I have made some search on this issue, most of the posts point to a dropdown list or a SelectList method using MVC, but for my case it is a Controller creation fail, so it seems to be an Entity Framework Core issue

Any help ?

JRB
  • 1,943
  • 1
  • 10
  • 9
Sami-L
  • 5,553
  • 18
  • 59
  • 87
  • Have you tried adding a parameterless constructor for `Todo`? – poke Oct 26 '17 at 20:25
  • I have tried several combinations found in tutorials but no one worked, here the controller takes "MainDbContext" as a constructor parameter, could you provide a snippet example with parameterless constructor? – Sami-L Oct 26 '17 at 20:38
  • I just fix, solution here [https://stackoverflow.com/questions/48854417/no-parameterless-constructor-defined-for-this-object-in-asp-netcore-migrations/59295949#59295949](https://stackoverflow.com/questions/48854417/no-parameterless-constructor-defined-for-this-object-in-asp-netcore-migrations/59295949#59295949) – azorlua Dec 12 '19 at 00:14

8 Answers8

5

Thanks to @poke comment above, and to this link: "Use Code First with connection by convention", by modifying the context class as follows C# will call base class parameterless constructor by default

  public class MainDbContext : DbContext
  {
    public MainDbContext()
    // C# will call base class parameterless constructor by default
    {
    }
  }
Sami-L
  • 5,553
  • 18
  • 59
  • 87
3

It's a tooling error. Most likely, you're running Visual Studio 2015, which doesn't have full .NET Core support. Basically, in previous versions of EF, DbContext had a parameterless constructor, and this version of the scaffold generator is depending on that. In EF Core, DbContext does not have a parameterless constructor, so the generator is choking on that.

If you're using VS2015, upgrade to 2017. It's time. Aside from that, you don't need this anyways, and it's only leading you down a bad path. All the scaffold does is create a new class under Controller, named {Name}Controller that inherits from Controller. Then it creates a folder named {Name} in Views and adds some basic HTML for doing CRUD. You'll end up replacing most of this HTML anyways. Additionally, the scaffold requires you to work with an actual entity class, which is the last thing you should ever be doing. You should always accept user input via a view model and then map that posted data onto your entity class before finally saving the entity. Look at the scaffold being broken as an excellent opportunity to start learning how to create good code.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • Great advises, currently I am using Asp.Net Core 2.0 / Entity Framework Core 2.0 with Visual Studio 2017. It seems these newly changed technologies still have alot of lacks, and I move very slowly because of issues. – Sami-L Oct 26 '17 at 22:56
1

Here's the solution from Microsoft. It suggest to create a design-time class that instantiates the connection to a database.

yW0K5o
  • 913
  • 1
  • 17
  • 32
0

A solution
Because DbContext constructor is expecting DbContextOptions, AddDbContext must be set within the Startup Configuration method.

public class MainDbContext : DbContext
      {
        public MainDbContext(DbContextOptions<MainDbContext> options) : base(options)
        {
        }

        public DbSet<Todo> Todo { get; set; }

      }

Within projects startup.cs set AddDbContext

services.AddDbContext<MainDbContext>(o => o.UseSqlServer(@"Data Source=SOURCE;Initial
Catalog=DBCatalog;User ID=ZX;Password=******;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;
ApplicationIntent=ReadWrite;MultiSubnetFailover=False"));

ConfigureServices method: Set database: UseSqlServer, UseInMemeoryDatabase, UseSqlite, etc...

    public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<MainDbContext>(o => o.UseSqlServer(@"Data Source=SOURCE;Initial
        Catalog=DBCatalog;User ID=ZX;Password=******;Connect
        Timeout=30;Encrypt=False;TrustServerCertificate=False;
        ApplicationIntent=ReadWrite;MultiSubnetFailover=False"));                            
            }
deDogs
  • 739
  • 1
  • 8
  • 24
0

Make sure your project builds and runs without errors before scaffolding.

In Visual Studio 2019, I received this error while attempting to scaffold a new controller because I had a missing comma in my JSON in appsettings.json file.

Eventually I built and tried to run and got a System.FormatException, "Could not parse the JSON file" during runtime. Since appsettings.json was the only JSON file I was editing recently I knew it had to be appsettings.json.

Scaffolding, code generators, and EF migrations invoke runtime code, this means even if your code compiles, if it throws runtime errors those could cause a problem for such actions.

FYI - As of EF Core 2.1 parameterized constructors are allowed. See this Microsoft article for more information. https://learn.microsoft.com/en-us/ef/core/modeling/constructors

CT0
  • 11
  • 1
0

the solution is check the file Startup.cs if you have in the void ConfigureServices the DataContext, for example in SQLServer my Startup.cs is

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddDbContext<YourDataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("YourConnectionStrings")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }
    }

if you not have this services the error is

no parameterless constructor defined for type YourDataContextName

Brayan Aguilar
  • 876
  • 8
  • 8
-1

I had the same problem and I add this line to Startup.cs on the ConfigureServices method. It worked fine for me:

       services.AddControllersWithViews();
jim
  • 9
  • 2
-3

Just add an empty constructor to your dbcontext and this solves the problem.