how to perform -disconnected- delete in many-to-many relationships (Entity Framework Code First)

百般思念 提交于 2019-12-11 22:56:27

问题


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 as Deleted.
  • 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!