Home > Mobile >  How to create relation one to many between IdentityUser model and another model
How to create relation one to many between IdentityUser model and another model

Time:08-11

I'm trying to create relation one to many beetwen IdentityUser model(inherits from IdentityUser class) and Comment model but I get an error: The relationship from 'Comment.WebAppUser' to 'WebAppUser.Comments' with foreign key properties {'UserId' : int} cannot target the primary key {'Id' : string} because it is not compatible. Configure a principal key or a set of foreign key properties with compatible types for this relationship. Problem is that IdentityUser model uses a string as primary key but in Comment model type of foreign key which is id of user is int.

The question is: How should I resolve this conflict? Should I change type of IdentityUser primary key for int (I know that i can do it, but won't that create problems because of the IdentityUser base class and its structure?) or maby convert forgein key for string?

public class Comment
{
    [Key]
    public int CommentId { get; set; }
    public int UserId { get; set; }
    public WebAppUser WebAppUser { get; set; }
}

public class WebAppUser : IdentityUser
{
    public IEnumerable<Comment> Comments { get; set; }       
}

 modelBuilder.Entity<Comment>()
       .HasOne<WebAppUser>(w => w.WebAppUser)
       .WithMany(c => c.Comments)
       .HasForeignKey(w => w.UserId);

If the option is to change the primary key of the WebApp User table, let me know what the consequences are and what and where I would have to change/add in the code.

CodePudding user response:

Changing Fk to string and changing the type of primary key of the WebAppUser are both available methods, But If you choose to change the type of PK in WebAppUser, you need to modify it according to the following code:

Model

public class WebAppUser : IdentityUser<int>
    {
        public IEnumerable<Comment> Comments { get; set; }
    }

Change:

public class ApplicationDbContext : IdentityDbContext

to

public class ApplicationDbContext : IdentityDbContext<WebAppUser,IdentityRole<int>,int>

Startup.cs

services.AddDefaultIdentity<WebAppUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

Now you change the type of pk to int successfully.

In my opinion, Change FK to string is easier than change PK to int in IdentityUser.

More details you can refer to this link

  • Related