Delete related elements in 1:N relation and not only inserts null in the foreign key

白昼怎懂夜的黑 提交于 2020-01-05 03:34:52

问题


I have the following class

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

ObjectA and ObjectB are in 1:N relation.

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

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

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'

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

Thanks.


回答1:


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);



回答2:


I think it is a case of Cascade Delete.

I'm not sure but I think you can set the cascade delete (in your application AND in your database) to allow EF to make deletion on cascade.

Maybe look at some documentation to find how to do that. It seems there is a lot of related questions on SO.

  • Example
  • Example2
  • Example3


来源:https://stackoverflow.com/questions/14381689/delete-related-elements-in-1n-relation-and-not-only-inserts-null-in-the-foreign

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