问题
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