Entity Framework Core 5 - Many-To-Many Issue


I'm trying to create an EF Core 5 DB Context with a many-to-many relationship between two tables.

My DBContext is as defined below.

public class ProjectMemberDbContext : DbContext
    public virtual DbSet<Project> Projects { get; set; }
    public virtual DbSet<Member> Members { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

    protected override void OnModelCreating(ModelBuilder modelBuilder)
            .HasMany(x => x.Members)
            .WithMany(x => x.Projects);

The Project and Member classes are defined:

public class Project
    // Simplified for brevity
    public int ID { get; set; } // Primary Key
    public string Name { get; set; }
    public int AuthorId { get; set; } // Foreign Key
    public Member Author {get;set;}
    public List<Member> Members { get; set; }
public class Member
    // Simplified for brevity
    public int ID { get; set; } // Primary Key
    public ulong SnowflakeId { get; set; }
    public List<Project> Projects { get; set; }

I am trying to add an existing member to a project. This is done by:

  1. Creating the new member
  2. Saving the new member to the database
  3. Loading the member from the database (the Member.ID is now defined)
  4. Creating a new project with the member as the author
  5. Adding the author to the Project's list of members

Here is the relevant snippet of code I'm using that reproduces this issue.

// Data access classes
var memberDal = new MemberDAL(connectionString);
var projectDal = new ProjectDAL(connectionString);

// Gettingthe Author from the members table.
var author = await memberDal.ReadAsync(1);

// Creating a new project
var project = new Project
    Name = "My Project",
    Author = author,

// Adding the author as a member.

Upon attempting to save these changes, I get the following error:

Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 19: 'UNIQUE constraint failed: MEMBER.MEMBER_ID'.

This issue doesn't occur if I create a new Member (instead of using the one that was retrieved in Step 3). Or if I don't add any members to the Project.Members list. It seems like I can't add existing members to a list of members in a project.

What gives? Can anyone advise?

asked on Stack Overflow Dec 8, 2020 by The Don • edited Dec 10, 2020 by Nick Martin

0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0