EF Core - Double key with many to many relationship

246 Views Asked by At

Project environment

  • EF Core 2.2.6
  • Many-to-Many, indirect via join table
  • Course records already exist on the database

As soon as I try to add a record to the join table, I get the following error message.

MySql.Data.MySqlClient.MySqlException (0x80004005): Duplicate entry '3945' for key 'PRIMARY'

Entites, Join Table

public class Course
{
    public long Id { get; set; }
    // Filled with reference object and Id of the reference object
    public ICollection<UserCourse> CourseUsers { get; set; }
}

public class User
{
    public long Id { get; set; }
    public ICollection<UserCourse> UserCourses { get; set; }
}

public class UserCourse
{
    public long UserId { get; set; }
    public User User { get; set; }

    public long CourseId { get; set; }
    public Course Course { get; set; }
}

Fluent API

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<UserCourse>()
        .HasKey(uc => new { uc.UserId, uc.CourseId });

    modelBuilder.Entity<UserCourse>()
        .HasOne(uc => uc.Course)
        .WithMany(c => c.Users)
        .HasForeignKey(uc => uc.CourseId);

    modelBuilder.Entity<UserCourse>()
        .HasOne(uc => uc.User)
        .WithMany(c => c.Courses)
        .HasForeignKey(uc => uc.UserId);
}

Considerations

The record of the course with the ID 3945 already exists in the database and this probably causes the error message. I don't know how to make EF create only the relationship in the join table and not the record in the course table.

Thanks in advance.

0

There are 0 best solutions below