© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
5 replies
Andrew

Many to Many with Entity Framework

I am an absolute newbie to EF, so keep that in mind.

I would have thought that if I had the following

class A
{
    public int Id { get; set; }
    public ICollection<B> B { get; set; } = [];  // Edit: forgot the property name
}

class B
{
  public int Id { get; set; }
}
class A
{
    public int Id { get; set; }
    public ICollection<B> B { get; set; } = [];  // Edit: forgot the property name
}

class B
{
  public int Id { get; set; }
}


and the following model creation

public DbSet<A> A {get; set;}
public DbSet<B> B {get; set;}

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

    // B doesn't have a loop back 
    // to A, but it's still a many-to-many relationship
    modelBuilder.Entity<A>()
        .HasMany<B>()
        .WithMany();
}
public DbSet<A> A {get; set;}
public DbSet<B> B {get; set;}

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

    // B doesn't have a loop back 
    // to A, but it's still a many-to-many relationship
    modelBuilder.Entity<A>()
        .HasMany<B>()
        .WithMany();
}


then if I needed to insert a new
A
A
I wouldn't have to do anything other than

await context.AddAsync(newA);
await context.SaveChangesAsync();
await context.AddAsync(newA);
await context.SaveChangesAsync();


but I'm getting an error with

Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table 'B' when IDENTITY_INSERT is set to OFF.
Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table 'B' when IDENTITY_INSERT is set to OFF.


I tried reading through the many-to-many docs but didn't find anything in particular: https://learn.microsoft.com/en-us/ef/core/modeling/relationships/many-to-many

I would have thought if the id already existed, then it would be inserting a relationship with the implicitly created mapping table. Is there a different way I should be adding
A
A
?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ Many-to-many relationship using Entity Framework
C#CC# / help
2y ago
Entity Framework Core Issue - Many to Many relationship
C#CC# / help
2y ago
Entity framework exception while creating a many to many relation
C#CC# / help
2y ago
Multiple 1 to Many Relationships in Entity Framework
C#CC# / help
2y ago