开发者

Entityframework 4: Problem with ForeignKey when removing a child entity from parents collection

开发者 https://www.devze.com 2023-01-07 18:45 出处:网络
New to the EF, I have an issue. OK, so, I have an Entity with a related Table (one-to-many relationship). The entity holds a collection of child objects from the related table.I want to remove an obj

New to the EF, I have an issue.

OK, so, I have an Entity with a related Table (one-to-many relationship). The entity holds a collection of child objects from the related table. I want to remove an object from the related collection but not from the child table.

However, when I call <entity>.myRelatedChildTable.Remove( childEntity ) and then call the _context.SaveChanges( ), I get an exception about ForeignKey Constraints. Now, if I call the _context.DeleteObject() and then _context.SaveChanges() we have no problem. But, now we have no child entity as well--it is deleted from the db.

here is the text of the Exception: 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.

anyone have an idea/suggestion how I can fix this?


It sounds like you're basically trying to decouple EF from the database. Unfortunately save changes pushes the changes back to the database which obviously you don't want. You can just not call SaveChanges and continue to work with the collection. EF will account for your deletion and not return that information. At the end you can discard your changes and move on.

If you do actually want to delete the item without deleting the child you can't in the current schema. You would have to allow nulls in the DB.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号