使用Asp.net Core生成带视图的Controller

时间:2017-02-25 23:50:32

标签: controller asp.net-core views asp.net-core-mvc

我使用的是项目asp.net核心但是当我想生成一个模型视图的控制器时我有一个错误:

  

创建DbContext实例以获取模型时出错。   没有为此对象定义的无参数构造函数。没有参数   为此对象定义的构造函数。在   Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b__6_0()   在   Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(字符串[]   args)at   Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(字符串[]   参数)

这是DBContext:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using WebApplication.Models;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using MySQL.Data.EntityFrameworkCore.Extensions;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Design.Internal;


namespace WebApplication
{
public class HunterViewContext : DbContext
{
    public HunterViewContext(DbContextOptions<HunterViewContext> options)
    : base(options)
    { }
    public DbSet<User> User{ get; set; }       
}
}

DBContextFactory:

using Microsoft.EntityFrameworkCore;
using MySQL.Data.EntityFrameworkCore.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication.Models
{
public static class HunterViewContextFactory
{
    public static HunterViewContext Create(string connectionString)
    {
        var optionsBuilder = new DbContextOptionsBuilder<HunterViewContext>   ();
        optionsBuilder.UseMySQL(connectionString);

        //Ensure database creation
        var context = new HunterViewContext(optionsBuilder.Options);
        context.Database.EnsureCreated();

        return context;
    }
    }
    }

模特:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Design.Internal;

namespace WebApplication.Models
{
public class User 
{

    public User()
    {

    }
        public int Id { get; set; }

        [MaxLength(30)]
        public string Name { get; set; }

        [MaxLength(50)]
        public string LastName { get; set; }
    }

    }

当我想为模型用户创建带视图的MVC控制器时出现错误

error

1 个答案:

答案 0 :(得分:1)

您是否尝试使用Visual Studio代码脚手架功能自动生成控制器类和视图?如果是这样,ASP.Net核心项目模板尚不支持它。 您需要自己创建视图和控制器类,请参阅文档Add Controllers

打开project.json文件并添加以下包依赖项和工具

在依赖关系部分

添加以下包

//代码生成器包生成控制器,视图

"Microsoft.VisualStudio.Web.CodeGenerators.Mvc": "1.0.0-preview2-final", 
"Microsoft.VisualStudio.Web.CodeGeneration.Tools": "1.0.0-preview2-final"

在工具部分

添加以下工具

//访问命令工具代码生成

"Microsoft.VisualStudio.Web.CodeGeneration.Tools": "1.0.0-preview2-final"

有关详细信息,请参阅Scaffolding in ASP.NET Core