C
C#2w ago
palapapa

Is it possible to remove a many-to-many relationship without using `Include` in EF Core?

Let's say there is a many-to-many relationship between A and B, and an entity a of type A with an ID of 1 is related to an entity b of type B with an ID of 2. Is it possible to remove this relationship without using context.A.Include(a => a.Bs)... or an explicit join table?
7 Replies
Angius
Angius2w ago
What do you mean "remove it"? .Include certainly does not remove any relationships
palapapa
palapapaOP2w ago
Basically I want to remove a row in the join table where the AId column is 1 and the BId column is 2 The only way I know is to use Include to populate the collection navigation property of A first, then remove the B instance with an ID of 2 from it, then call SaveChanges
Angius
Angius2w ago
var j = await context.Joins
.Where(jt => jt.AId == a && jt.BId == b)
.FirstOrDefaultAsync();
context.Joins.Remove(j);
await _context.SaveChangesAsync();
var j = await context.Joins
.Where(jt => jt.AId == a && jt.BId == b)
.FirstOrDefaultAsync();
context.Joins.Remove(j);
await _context.SaveChangesAsync();
or
await context.Joins
.Where(jt => jt.AId == a && jt.BId == b)
.ExecuteDeleteAsync();
await context.Joins
.Where(jt => jt.AId == a && jt.BId == b)
.ExecuteDeleteAsync();
would work
palapapa
palapapaOP2w ago
I don't want to use an explicit join table
Angius
Angius2w ago
Tough
Anton
Anton2w ago
You should be able to There should be shadow properties for this stuff And you can get the table by name Or from a relationship
Angius
Angius2w ago
If you have a property referencing the JoinTable, sure But that would require that JoinTable to exist in code Ergo, explicit join table one way or another

Did you find this page helpful?