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));
}
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
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.
Startup.cs - the database context should be registered with the correct connection string.
Appsetting.json - the connection string should be correctly typed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With