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

asp.net-core asp.net-core-2.0 asp.net-mvc-scaffolding entity-framework-core visual-studio-2017

Question

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?

1
0
6/11/2017 5:02:18 AM

Popular Answer

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.

2
6/10/2017 10:56:15 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow