VS 2013 Controller Scaffolding Fails for the ApplicationUser Model (Multiple object sets per type are not supported)

AKhooli picture AKhooli · Nov 10, 2013 · Viewed 11.5k times · Source

In a VS 2013 RTM, MVC 5 project with EF 6, I tried to scaffold a controller based on the ApplicationUser (default with individual accounts authentication). Both ApplicationUser and IdentityUser are mapped to a Users table. The wizard opens the context file for editing and tries to add a new db set for ApplicationUser (ApplicationUsers) and then fails with this error:

Unable to retrieve metadata for ApplicationUser. Multiple object sets per type are not supported. The object sets ApplicationUsers and Users can both contain instances of type ApplicationUser The solution does not have any reference to, or instance of ApplicationUsers.

Is this a known issue? Can the scaffolding be run using command line with options (from PMC)? Note: scaffolding also adds an extra db set to the context class if I specify a model that references ApplicationUser (the app works if I remove it and fix references in the generate controller).

Answer

Chris Pratt picture Chris Pratt · Aug 26, 2014

Wow. I'm really surprise that no one actually got to the root of this, and instead, are just recommending workarounds.

IdentityDbContext already contains a property:

`public virtual IDbSet<TUser> Users { get; set; }

When you subclass IdentityDbContext to create your own application-specific context, you must specify what class satisfies the TUser generic. The default is:

public ApplicationDbContext : IdentityDbContext<ApplicationUser>

Which then means that you functionally have a property already via inheritance in the form of:

public IDbSet<ApplicationUser> Users { get; set; }

If you then add another property to your application-specific context such as:

public DbSet<ApplicationUser> ApplicationUsers { get; set; }

You now have the same entity tracked by two DbSets, and you get that error. The solution? Simply don't add your own DbSet for ApplicationUser. There's no need to rename or override anything.