We have two tables, table1 and table2, defined in SQL, that have a many-to-many relationship.
As is the usual practice, we've implemented this by creating an intersection table, table1_table2, that contains the primary keys of table1 and table2.
And we've created 1-many FKs from table1 to table1_table2 and from table2 to table1_table2.
Then we had EF6 create an EDMX, using import from database.
The model defined two entities, table1s and table2s, with a many-to-many relationship.
That is, there is the POCO class table1 contains an ICollection table2s, and class table2 contains an ICollection table1s.
How do I clear the connection, so that I can delete all the instance of table1?
This:
using (var dbContext = new DbContext())
{
dbContext.table1s.RemoveRange(dbContext.table1s);
dbContext.SaveChanges();
}
Throws an exception:
System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_table1_table2_table1".
I tried nulling out the relationship, first:
using (var dbContext = new DbContext())
{
foreach (var table1 in dbContext.table1s)
table1.table2s = null;
dbContext.table1s.RemoveRange(dbContext.table1s);
dbContext.SaveChanges();
}
And I get the same exception.
So I tried removing each table2 record explicitly:
using (var dbContext = new DbContext())
{
foreach (var table1 in dbContext.table1s)
{
foreach (var table2 in table1.table2.ToList()
{
table1.table2s.Remove(table2);
}
}
dbContext.table1s.RemoveRange(dbContext.table1s);
dbContext.SaveChanges();
}
And that seems to work, but it's so tedious that I have a hard time believing that that is the way that I'm supposed to be doing this.
Ideas?