C#C
C#2y ago
prodijay

Unable to set User FK in another model (User extends IdentityUser)

I am attempting to establish relationships between my models. For context I'm using EntityFrameworkCore and Identity.
I have a User model (extends IdentityUser) and a Study model.
Studies should have one User, and Users can have multiple Studies.
The first time I tried to establish the relationships I wrote them in the models, like so:
c#
  // Study.cs
  public class Study
  {
    public int Id { get; set; }
    //...
    public required string UserId { get; set; }
    public IdentityUser? User { get; set; }
  }


c#
  // User.cs
    public class User : IdentityUser
  {
    public List<Study> Studies { get; set; } = new List<Study>();
  }


That resulted in the warning The foreign key property 'Study.UserId1' was created in shadow state because a conflicting property with the simple name 'UserId' exists in the entity type, but is either not mapped, is already used for another relationship, or is incompatible with the associated primary key type.

I am now trying to use OnModelCreating to create the relationships in DBContext instead, like so:
c#
  public class ApplicationDbContext : IdentityDbContext<IdentityUser>
  {
    public DbSet<User> Users { get; set; }
    public DbSet<Study> Studies { get; set; }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    { }

    protected override void OnModelCreating(ModelBuilder builder)
    {
      base.OnModelCreating(builder);

      builder.Entity<Study>()
      .HasOne(s => s.User)
      .WithMany(u => u.Study)
      .HasForeignKey(s => s.UserId)
    }
  }

However this says that IdentityUser does not contain a definition for Study and no accessible extension method 'Study' accepting a first argument of type 'IdentityUser' could be found

I have henceforth changed public IdentityUser? User { get; set; } to public User? User { get; set; } with the same result.
However User should contain a list of Study objects...
Was this page helpful?