删除1:N关系中的相关元素,不仅在外键中插入null [英] Delete related elements in 1:N relation and not only inserts null in the foreign key

查看:77
本文介绍了删除1:N关系中的相关元素,不仅在外键中插入null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程

public class ObjectA{
   private List<ObjectB> list;    
}

ObjectA ObjectB 处于1:N关系。

ObjectA and ObjectB are in 1:N relation.

我想删除一些ObjectB实例,并使用:

I want to delete some of ObjectB instances and I use:

 while (objectA.list.Any())
        objectA.list.Remove(objectA.list.First());




  • 关系表的列表-

    • List is of the relation table -

      List<ObjectAobjectB>
      


    • 在数据库中,我将关联定义为可为空的外键,否则会得到

      In the Database I have defined therelation as a nullable foreign key otherwise I get


      操作失败:由于一个或多个
      ,关系无法更改外键属性不可为空。对关系进行更改时,会将相关外键属性
      设置为空值。如果外键不
      支持空值,则必须定义新的关系,必须为外键属性
      分配另一个非空值,或者必须删除不相关的对象。

      现在它是可空的外键,

      当我运行sql分析时,我得到以下信息:

      So now that it is Nullable foreign key,
      When I run sql profiling I get the following:

      exec sp_executesql N'update [Schem].[ClassB]
      set [ClassAID] = null
      where ([Id] = @0)
      ',N'@0 uniqueidentifier',@0='092CE959-370A-4785-AF4A-93A0E4952C59'
      

      它只是在关系中输入null而不是删除对象。

      我在做什么错了?

      It just enters a null in the relation instead of deleting the object.
      What am I doing wrong?

      谢谢。

      推荐答案

      objectA.list.Remove(objectA.list .First()); 删除关系,而不是实际实体。如果要从数据库中删除objectB,则必须从上下文中将其删除,例如:

      objectA.list.Remove(objectA.list.First()); is removing the relationship, not the actual entity. If you want to delete the objectB's from the database then you have to remove them from the context like so:

      foreach(var item in objectA.list.ToList())
          context.ObjectBs.Remove(item);
      

      这篇关于删除1:N关系中的相关元素,不仅在外键中插入null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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