【发布时间】:2020-03-08 13:57:15
【问题描述】:
我正在尝试搭建脚手架,但出现以下错误:
运行所选代码生成器时出错:'没有为类型'MvcProduct.Data.MvcProductContext'定义无参数构造函数。'
以下是我的MvcProductContext:
using Microsoft.EntityFrameworkCore;
using MvcProduct.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MvcProduct.Data
{
public class MvcProductContext : DbContext
{
public MvcProductContext(DbContextOptions<MvcProductContext> options)
: base(options)
{
}
public DbSet<Product> Product { get; set; }
}
还有appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"MvcProductContext": "Server=(localdb)\\mssqllocaldb;Database=MvcProductContext-1;Trusted_Connection=True;MultipleActiveResultSets=true"
}
ConfigureServices 方法在 Startup.cs 文件中:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<MvcProductContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MvcProductContext")));
}
我还尝试在 MvcProductContext 类中添加第二个构造函数。 (我想避免并且不想做的事情)没有任何参数的第二个构造函数。但如果我这样做,我只会得到另一个错误,上面写着:
运行所选代码生成器时出错:'没有为此 DbContext 配置数据库提供程序。可以通过覆盖
DbContext.OnConfiguring方法或在应用程序服务提供程序上使用AddDbContext来配置提供程序。如果AddDbContext在应用程序服务提供者上。如果使用了AddDbContext,则还要确保您的DbCotnext类型在其构造函数中接受DbContextOptions<TContext>对象并将其传递给DbContext的基本构造函数。
微软也是如此。他们正在使用实体框架构建带有视图的 MVC 控制器。他们没有在 MvcMovieCONtext 类中添加第二个构造函数就这样做了。他们的 MvcMovieContextClass 对应于我的 MvcProductContext 类。
任何帮助将不胜感激。
【问题讨论】:
-
你需要无参数的构造函数。您还需要在应用程序配置中包含对连接字符串的引用
-
@Glenn Ferrie 好的,但微软为什么不在他们的示例中包含无参数构造函数?此外,当我在 MvcProductContext 中已有的构造函数下方添加一个无参数构造函数时,我收到了另一个错误,该错误已在帖子中。关于包含对连接字符串的引用,我认为我是在 ConfigureServices 方法的 startup.cs 文件中这样做的?我已使用 Startup.cs 文件中的代码更新了原始帖子。
-
这看起来应该可以了,你安装了什么版本的.net core sdk? (在 cmd 行运行:dotnet --info)。与 Microsoft 示例中使用的版本相同吗?
-
我无法重现该问题。它仅在您忘记注册 dbcontext 但您已从代码中添加时出现。您可以在全新的 mvc 项目中尝试吗?
-
@Andrew 我有版本:3.0.100。在 Visual Studio 2019 中,我选择了 3.0 作为项目版本,并且我也选择了 Microsoft guide to 3.0。
标签: c# entity-framework model-view-controller asp.net-core-mvc asp.net-mvc-scaffolding