mneumann
mneumann

Reputation: 786

Extend IdentityUser, foreign key constraint conflict

I want to use ASP.Net-Identity for user management. For this, I want to extend the IdentityUser class with a few attributes.

public class AppUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<AppUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    } 

    public int Settings_ID { get; set; }
    public string Position { get; set; }
    public string CompanyName { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
[...]

Now, in my data context, I want to create just one table for this user model:

 public class AntContext : IdentityDbContext<AppUser>
{

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<AntContext>(null);
        modelBuilder.Entity<AppUser>().ToTable("AppUsers");
        base.OnModelCreating(modelBuilder);
    }
        public override IDbSet<AppUser> Users { get; set; }
[...]

However, when trying to update-database, I receive the error:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.AppUsers_dbo.AspNetUsers_Id". The conflict occurred in database "C:\USERS\NEUMA\SOURCE\REPOS\MYANTON\MYANTON\APP_DATA\ASPNETDB.MDF", table "dbo.AspNetUsers", column 'Id'.

I understand that AspNetUsers is a table from IdentityUser, but how do I create only one table so that there are no conflicts?

How do I properly extend the IdentityUserclass and use it in my data context?

Upvotes: 0

Views: 272

Answers (1)

user4864425
user4864425

Reputation:

The solution is to not mix contexts. Maintain a seperation of concerns. Use the migration script for Identity and create a new script for the business context (your data context).

Add a Users table to the business context that references the name or sub from the IdentityContext. Please read my answer here for a quite similar question.

Also, there is no need to extend the ApplicationUser table. You can use AspNetUserClaims to add this kind of information. With a custom type:

new Claim("http://www.myapp.com/Firstname", "Firstname");

Or an existing WIF ClaimType:

new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname", "Lastname");

As for CompanyName, this may actually be part of the business context.

Upvotes: 1

Related Questions