2

I'm new to all this Entity Framework stuff, so excuse me in advance.

I'm trying to integrate ASP.NET Identity to my project. I've got an existing database, mapped and ready, and I'm using Code First with automatic migrations. What I'm trying to do is have Identity only to store username, password and some other fields and the rest of the information needs to be stored in another table, called Contact, so I need 1:1 connection from my Identity to my that table.

What I've tried so far is merging all in one context, so what I've got is:

public partial class pmdb02Context : IdentityDbContext
{
    static pmdb02Context()
    {
        Database.SetInitializer<pmdb02Context>(null);
    }

    public pmdb02Context()
        : base("pmdb02Context")
    {
    }

    --- Lots of DbSets ---

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

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        --- Lots of Mappings ---

        modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
        modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
        modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
        modelBuilder.Entity<ApplicationUser>().ToTable("IdentityUsers", "dbo");    
    }
}

When I get to:

var result = await UserManager.CreateAsync(user, model.ContactData.Password);

I receive this:

IdentityUser_Logins_Target: : Multiplicity is not valid in Role 'IdentityUser_Logins_Target' in relationship 'IdentityUser_Logins'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:

My ApplicationUser class looks like this:

public class ApplicationUser : IdentityUser
{
    public int ContactId { get; set; }
    public bool? IsCurrent { get; set; }

    public virtual Contact Contact { get; set; } 
}

So, I need a relation to Contact. My problem, I guess, is in the way I'm trying to get these to things to work together at all, I've been trying to do so all day yesterday and today as well.

I'd really appreciate any help. Thanks!

brnt
  • 108
  • 1
  • 8

1 Answers1

0

Finally fixed my issue yesterday. Turns out the main source of my problem was in this line:

Database.SetInitializer<pmdb02Context>(null);

When I changed it to:

Database.SetInitializer<pmdb02Context>(new MigrateDatabaseToLatestVersion<pmdb02Context, Configuration>());

Identity finally worked as supposed to, I only added the relationship to Contact as usual.

brnt
  • 108
  • 1
  • 8