我正在尝试构建脚手架,但出现以下错误:
There was an error running the selected code generator: 'No parameterless constructor defined for type '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
中添加第二个构造函数 类。 (我想避免和不想做的事情)没有任何参数的第二个构造函数。但如果我这样做,我只会收到另一个错误:
There was an error running the selected code generator: 'No database provider has been configured for this DbContext. A provider can be configured bu overriding the
DbContext.OnConfiguring
method or by usingAddDbContext
on the application service provider. IfAddDbContext
on the application service provider. IfAddDbContext
is used, then also ensure that yourDbCotnext
type accepts aDbContextOptions<TContext>
object in its constructor and passes it to the base constructor forDbContext
.
微软也在做同样的事情。他们正在使用 Entity Framework 搭建一个带有 View 的 MVC Controller 。他们这样做时没有在他们的 MvcMovieCOntext 类中添加第二个构造函数。它们的 MvcMovieContextClass 对应于我的 MvcProductContext 类。
如有任何帮助,我们将不胜感激。
最佳答案
只需添加一个IDesignTimeDbContextFactory实现到您的项目并再次尝试搭建脚手架。它将负责实例化您的 DbContext。
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<MvcProductContext>
{
public MvcProductContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appSettings.json")
.Build();
var builder = new DbContextOptionsBuilder<MvcProductContext>();
var connectionString = configuration.GetConnectionString("MvcProductContext");
builder.UseSqlServer(connectionString);
return new MvcProductContext(builder.Options);
}
}
关于c# - 为什么脚手架没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58825770/