It is common practice in O/RMs to delete an entity without actually loading id, just by knowing its id. This saves one SELECT and is great for performance. For example, using Entity Framework Code First:
This, however will fail if there is a [Required] reference (might be defined in fluent configuration, it doesn’t matter) to another entity (many-to-one, one-to-one)! For example, if our Product entity would have something like this:
In this case, the required constraint is treated like a concurrency check and the above query will fail miserably. From conversations with the EF team, I understood this is related with some EF internals, which apparently are difficult to change.
There are three workarounds, though:
The third option would be to have something like:
It really shouldn’t be required to have this foreign key – that’s what navigation properties are meant to replace – but it is. Let’s hope that some future version of EF will fix this.