问题
I have the following code for adding a record to many-to-many relationship in a disconnected way. I wonder if it is possible to achieve a delete operation with disconnected approach.
using (var db = new FMyDbContext())
{
int selectedTeamId = Convert.ToInt32(lst_AllTeams.SelectedValue);
Team myTeam = new Team() { TeamId = selectedTeamId };
int selectedCompId = Convert.ToInt32(grd_Competitions.SelectedValue.ToString());
Competition myComp = new Competition() { CompetitionId = selectedCompId };
myComp.ParticipatingTeams = new List<Team>() { myTeam };
db.Entry(myComp).State = System.Data.Entity.EntityState.Unchanged;
db.Entry(myTeam).State = System.Data.Entity.EntityState.Unchanged;
db.SaveChanges();
};
This works well for inserting. How can I follow a similar approach when deleting? Basically, I do not want to fetch any records from the database. I am looking for a solution without executing an SQL statement with ExecuteStoreCommand.
回答1:
This simply isn't possible. In many-to-many associations with a hidden junction entity you can only work with independent associations. This is the type of association without a foreign key property exposed in the class model: there is no foreign key between Team and Competition.
So you have to load a collection before removing items form it.
If you really want to avoid this you can do two things:
- Pull the junction class (
CompetionTeam) into your model. Now you can create stub entities for the junctions, and mark them asDeleted. - Create a second context class that has a
DbSet<CompetionTeam>and use that context to manipulate junctions directly.
The latter option is a less common thing to do, but it's perfectly valid. But pulling the junction class into your model is probably the best thing to do, because often, sooner or later people will want to store information about the association. This is only possible when the class is part of the model.
来源:https://stackoverflow.com/questions/33437970/how-to-perform-disconnected-delete-in-many-to-many-relationships-entity-frame