Controller scaffolding doesn't work in VS 2017

2019-09-15 19:29发布

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

enter image description here

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:enter image description here

Okay, I added parameterless constructor to ApplicationDBContext:

public ApplicationDbContext() { }

And got the following error:enter image description here.

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?

2条回答
劳资没心,怎么记你
2楼-- · 2019-09-15 19:56

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.

enter image description here

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.

查看更多
姐就是有狂的资本
3楼-- · 2019-09-15 20:14

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

查看更多
登录 后发表回答