在MVC中支持读取操作"没有为此对象定义的无参数构造函数."

Thr*_*gic 10 entity-framework asp.net-mvc-5

我正在研究基本的MVC5/EF6应用程序,当我尝试在MVC中构建一个Read Action时遇到以下错误:

Error 

There was an error running the selected code generator: 
'No Parameterless constructor defined for this object'
Run Code Online (Sandbox Code Playgroud)

它不应该需要它,因为我调用的是读取而不是删除或更新,但是有问题的模型确实有一个无参数构造函数(就像下面的模型一样).

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()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

我的控制器在下面,它还有一个无参数构造函数:

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));
}
Run Code Online (Sandbox Code Playgroud)

Thr*_*gic 10

错误消息有点误导.有一个参数需要较少的构造函数,但它不是需要它的datacontext的模型.

  • 这些答案含糊不清.你们可以提供要删除的文件和代码行吗? (5认同)

Vec*_*ria 10

由于无法连接到数据库,我在ASP.NET Core MVC应用程序上遇到此错误.我花了几个小时检查我的模型和dbContext类只是为了意识到它们没有任何问题.该应用程序只是无法连接到数据库.我必须检查两个地方.

  1. Startup.cs - 应使用正确的连接字符串注册数据库上下文. 在此输入图像描述

  2. Appsetting.json - 应正确键入连接字符串. 在此输入图像描述