开发者

Why does InvalidOperationException get thrown when deleting some entity instances, while UpdateException gets thrown for others

I have a one-to-many relationship defined for two entities, let's just say Customer and Order. The relationship states that a Customer object can have many Order objects, but that an Order must have one Customer...a pretty standard 1:M relationship.

I have no cascading rules configured on the database and OnDeletes are set to None in my entity data model. This means deleting a customer that has orders will not be allowed.

My problem is that when the user in my application deletes a customer (that may have orders), I want to catch the exception that is thrown by enforcing the foreign key constraints. For one specific customer that has 33 orders, I get InvalidOperationException but for another customer that only has 2 orders, I get UpdateException. EF is letting the second delete statement go to the database and the database is returning the error that EF makes the UpdateE开发者_Python百科xception for. In the first scenario, EF doesn't even let the delete statement go to the database, it just says this is going to be invalid, because this entity instance of Customer contains Orders.

Can anybody explain why this behavior is happening?


There can be two different exceptions because there are two layers where this check is applied. First if you mark an object as deleted and execute SaveChanges EF will check its internal storage where all loaded objects are tracked. If EF finds that any tracked order related to the deleted customer is also not marked as deleted it will fire an exception (probably InvalidOperationException). If there is no tracked related order EF will execute delete operation in the database where FK relation triggers an error. This error is captured by EF and an exception is throwm (probably UpdateException with inner database related exception).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜