lycian
lycian
CC#
Created by lycian on 4/14/2024 in #help
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 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?
6 replies