Controller scaffolding doesn't work in VS 2017 preview for ASP.NET Core 2 Preview

感情迁移 提交于 2020-01-17 14:47:52

问题


I'm trying to use scaffolding to generate MVC Controller with views, using Entity Framework:

I created ApplicationDBContext:

public class ApplicationDbContext : DbContext
    {        

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }           

        public DbSet<med1.Models.House> House { get; set; }
    }

and added to ConfigureServices:

services.AddDbContext<Data.ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

And of course I have House model:

public class House
{
    public int ID { get; set; }
    public string HouseName { get; set; }
    public string Address1 { get; set; }
    public int CityID { get; set; }
    public City City { get; set; }
    public string ZIP { get; set; }
    public int StateID { get; set; }
    public State State { get; set; }
}

I got following error:

Okay, I added parameterless constructor to ApplicationDBContext:

public ApplicationDbContext() { }

And got the following error:.

Actually I had the same problem with previous project and created Controller and View manually.

But for this project I'd like to use scaffolding.

I'm doing something wrong or it's VS 2017 preview problem?


回答1:


You may be missing this part -

public class AppDbContextFactory : IDbContextFactory<AppDbContext>
{
    public AppDbContext Create(string[] args) =>
        Program.BuildWebHost(args).Services.GetRequiredService<AppDbContext>();
}

Once you enable scaffolding in your ASP.NET Core 2.0 project and created model name as 'House', follow these steps-

Step1: Right click on the Controllers folder in Solution Explorer and select Add > New Scaffolded Item.

Step2: Select 'MVC Controller with View, using Entity Framework' and click on Add.

Step3: In Add Controller, select House Model and use plus(+) sign to create new AppDbContext. It will also add above mentioned AppDbContextFactory.

After finishing step3, you will have HousesController in Controllers folder and corresponding Houses folder inside views folder.

This is my AppDbContext looks like-

public class AppDbContext : DbContext
{
    public AppDbContext (DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    public DbSet<AspNetCore200_VS2017preview1_scaffolding.Models.House> House { get; set; }
}

Hope this helps to proceed further.




回答2:


Copy contents of the following path of your application "bin\Debug\netcoreapp1.1" to "bin\MCD\Debug\netcoreapp1.1"

This solved the issue for me



来源:https://stackoverflow.com/questions/44469361/controller-scaffolding-doesnt-work-in-vs-2017-preview-for-asp-net-core-2-previe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!