简体   繁体   中英

EF6 with IdentityDbContext many to many invalid column name

I have an IdentityDbContext in which the ApplicationUser : IdentityUser has a double self referencing table to map FriendShip between different members:

public class ApplicationUser : IdentityUser
{
    public virtual ICollection<ApplicationUser> Friends { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ApplicationUser>().HasMany(x => x.Friends).WithMany();

        //I've tried the commented out section with no success
        //modelBuilder.Entity<ApplicationUser()
        //.HasMany(x=>x.Friends).WithMany().Map(x=>
        //{ 
        //    x.MapLeftKey("Friend1"); 
        //    x.MapRightKey("Friend2"); 
        //    x.ToTable("Friendship"); 
        //});
        base.OnModelCreating(modelBuilder);
    }

And then I try to add a new user to the db:

 void AddUser()
    {
        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());
        var user = new ApplicationUser { UserName = "HelloWorld" };
        manager.Create(user, "password1");
    }

This throws an EntityCommandExecutionException: "Invalid column name 'ApplicationUser_Id'." If I drop the many to many relationship it all works but it would be nice to have that relationship in the project.

The column name is the default given to the new relation table with the other one being ApplicationUser_Id1, I figured changing the column names might help but it didnt work(the commented out part).

Also it's strange that this column name is the reason for the exception because inserting a user to the db has nothing to do with that table, I'm lost here.

Any advice/suggestion is much appreciated.

I found the answer here

So, your mapping will be:

modelBuilder.Entity<ApplicationUser()
    .HasMany(x=>x.Friends).WithMany();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM