如何在多对多关系中执行-disconnected-delete(实体框架代码优先) [英] how to perform -disconnected- delete in many-to-many relationships (Entity Framework Code First)

查看:142
本文介绍了如何在多对多关系中执行-disconnected-delete(实体框架代码优先)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,用于以断开连接的方式将记录添加到多对多关系。我想知道是否可以通过断开方法实现删除操作。

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.

推荐答案

这根本就不是可能。在具有隐藏连接实体的多对多关联中,您只能使用 独立协会 。这是没有在类模型中暴露的外键属性的关联类型: Team 竞争

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:


  • 拉接头类( CompetionTeam )进入你的模型现在您可以为路口创建存根实体,并将其标记为已删除

  • 创建第二个上下文类,其中包含 DbSet< CompetionTeam> 并使用该上下文直接操纵路口。

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

这篇关于如何在多对多关系中执行-disconnected-delete(实体框架代码优先)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆