Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaffolding a Read Action in MVC "No parameterless constructor defined for this object."

I'm working on a basic MVC5/EF6 application and am running into the following error when I try to scaffold a Read Action in MVC:

Error 

There was an error running the selected code generator: 
'No Parameterless constructor defined for this object'

It should not need it anyway because I am calling a read not a delete or an update however the model in question does have a parameterless constructor (as do the models below it).

public class Article
{
    public int ArticleID { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public DateTime PublishDate { get; set; }

    public virtual Author Author { get; set; }

    public Article()
    {
    }
}

My controller is below and it also has a parameterless constructor:

public ArticleController()
{
    connection = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    context = new TRNContext(connection);
}

// GET: Article
public ActionResult Index(int id)
{
    return View(context.Articles.SingleOrDefault(a => a.ArticleID == id));
}
like image 681
Three Value Logic Avatar asked Apr 24 '15 10:04

Three Value Logic


3 Answers

There is also a scenario with aspnet core where the Program class isn't exposing IWebHostBuilder so that design time dbcontext creation can function properly.

I spent a few hours trying to solve this error with an aspnet core 2.2 mvc app.

Take a look at this link to understand how ef core tooling works. Re-writing my Program class to support application services solved it for me since my dbcontext didn't use a parameterless constructor. https://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation

like image 169
brady321 Avatar answered Nov 08 '22 17:11

brady321


I came across this error on an ASP.NET Core MVC application due to the failure to connect to the database. I spent hours checking my models and dbContext class only to realize there was nothing wrong with them. The application was just failing to connect to the database. There were two places I had to check.

  1. Startup.cs - the database context should be registered with the correct connection string. enter image description here

  2. Appsetting.json - the connection string should be correctly typed. enter image description here

like image 14
Vectoria Avatar answered Nov 08 '22 18:11

Vectoria


The error message was slightly misleading. There was a parameter less constructor required but it was not the model it was the datacontext that needs it.

like image 10
Three Value Logic Avatar answered Nov 08 '22 17:11

Three Value Logic