ObiEff ObiEff - 29 days ago 7
C# Question

Error Key Already Exists in Table when scaffolding controller vs2015

I am trying to follow the Music Store Example in Professional MVC 4 using VS2015. I am having issues scaffolding the music store controller. Everytime I try to create the controller a Error window pops up and the only information in it is: "There was an error running the selected code generator:'Key already exists in table.'"

I have searched around for this specific errors but most of the scaffolding error solutions seem to be about errors in the web.config, yet nothing has even changed in my web.config, it is the default one created when the new project was created.

I have tried creating another MVC project and coding the models again yet I still receive the error.

I am using Microsoft Visual Studio Enterprise 2015 version 14.0.247200 Update 1 if that helps.

The Classes that I have created in the Models folder are as follows and are exactly as they are in the book:

public class Album
{
public virtual int AlbumId { get; set; }
public virtual int GenreId { get; set; }
public virtual int ArtistId { get; set; }
public virtual string Title { get; set; }
public virtual decimal Price { get; set; }
public virtual string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
}

public class Artist
{
public virtual int ArtistId { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
}

public class Genre
{
public virtual int GenreId { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual List<Album> Albums { get; set; }
}


Thanks for your help

Answer Source

I had the same problem. I'm using Visual Studio Communitty 2015. Try a Model Class with the code:

public class MusicStoreDB : DbContext
{
    public MusicStoreDB() : base("name=MusicStoreDB")
    {
    }

    public DbSet<Album> Albums { get; set; }
    public DbSet<Artist> Artists { get; set; }
    public DbSet<Genre> Genres { get; set; }
}

At the add controller window, use MusicStoreDB as the context.

Working code can be found here.

The code for Chapter 4 looks like it has been generated from database so MusicStoreDB class is slightly different.