Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework and UPDATE CASCADE

A bit frustrated over here. I'm trying to find a way to support update cascading with the entity framework, and there doesn't seem to be a built-in way. Research on the net basically shows everyone saying that you should never change a primary key value anyway, but there are valid cases where you would need to (e.g. a UPC value as a primary key, and UPC barcodes are now becoming larger which means updating the existing ones and maintaining proper foreign key relationships).

One approach is apparently to tap into the SavingChanges event, see if the primary key fields are changing, and if so traverse the navigation properties and update the sub tables that way.

This, in theory, would work. But it just sounds cumbersome. Anyone have a better idea? Can't believe Bill would have left this stuff out of the framework just because most people don't do it. SQL Server still supports it ...

Thx!

like image 777
David Catriel Avatar asked Nov 05 '22 06:11

David Catriel


1 Answers

You cannot change the primary key directly via EF. The problem is that EF makes changes where primary key = x. So you cannot change x.

You could execute a stored procedure from EF that would update a primary key.

In your case with barcodes, I would have a primary key that is an auto increment number, then a barcode as a different field with a unique index.

like image 181
Shiraz Bhaiji Avatar answered Nov 13 '22 18:11

Shiraz Bhaiji