Home > Mobile >  EF Core - unknown relationship define foreign key
EF Core - unknown relationship define foreign key

Time:01-12

I want to link the default IdentityUser with a custom generic class called Permission<TUser> where is this case TUser = IdentityUser. The class is defined as follows:

public class Permission<TUser> {
    public TUser User { get; set; }
    public string Identifier { get; set; }
    public IEnumerable<string> Restrictions { get; set; }
}

The Identifier is the type of permission and NOT unique. That means the model only has a composite pk using the foreign key of the user and the permission identifier. That's what I defined:

builder.Entity<Permission<IdentityUser>>()
       .HasKey(p => new {p.User, p.Identifier});

But to set the foreign key of the permission I have to define a relationship and I don't know which one this is.

CodePudding user response:

It seems that you have a one-to-many relationship from IdentityUser to Permission, so:

builder.Entity<Permission>()
    .HasOne<IdentityUser>(p => p.User)
    .WithMany();

EF Core will assign a foreign key by convention. If your navigation property is 'User' then the FK will be 'UserId'.

You can override the Foreign key by continuing the above configuration with:

.HasForeignKey("IdentityUserId");
  •  Tags:  
  • Related