Cod*_*ent 5 c# model-view-controller entity-framework asp.net-mvc-scaffolding asp.net-core-mvc
我正在尝试搭建脚手架,但出现以下错误:
运行所选代码生成器时出错:“没有为类型‘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; }
}
Run Code Online (Sandbox Code Playgroud)
还有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"
}
Run Code Online (Sandbox Code Playgroud)
ConfigureServices文件中的方法Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<MvcProductContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MvcProductContext")));
}
Run Code Online (Sandbox Code Playgroud)
我还尝试在MvcProductContext类中添加第二个构造函数。(我想避免并且不想做的事情)没有任何参数的第二个构造函数。但如果我这样做,我只会收到另一个错误:
运行所选代码生成器时出错:“尚未为此 DbContext 配置数据库提供程序。可以通过覆盖该
DbContext.OnConfiguring方法或通过AddDbContext在应用程序服务提供者上使用来配置提供者。如果AddDbContext在应用服务提供商上。如果AddDbContext使用 ,那么还要确保您的DbCotnext类型DbContextOptions<TContext>在其构造函数中接受一个对象并将其传递给 的基本构造函数DbContext。
微软也在做同样的事情。他们使用实体框架用视图构建 MVC 控制器。他们这样做时没有在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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1314 次 |
| 最近记录: |