concurrency - Avoid inserting duplicate records in Entity Framework -


i have typical scenario users enter data inserted sql database using entity framework 6.0. however, rows part of entity need unique (already enforced unique key constraints in database).

to avoid possible concurrency or performance issues favour these checks left done sql server.

when attempting save new entity holds duplicate row, dbupdateexception thrown entity framework. inner exception sqlexception number equal 2627, , message reads:

"violation of unique key constraint 'uk_mytable_myrule'. cannot insert duplicate key in object 'dbo.mytable'".

considering there several tables involved, may each have own unique constraints defined, there no better way conclude friendlier message user reads:

"a myentity name 'myentity1' exists."

...without having infer through number , message properties sqlexception?

for example:

try {     ...     context.savechanges(); } catch (dbupdateexception exception) {     var sqlexception = exception.innerexception sqlexception;      bool isduplicateinmytable3 =         sqlexception != null &&         sqlexception.number = 2627/*unique constraint violation*/ &&         sqlexception.message.contains("'uk_mytable3_");      if (isduplicateinmytable3)     {         return "a mytable3 " + ... + " exists.";     }      throw exception; } 

is there "cleaner" way achieve same not involve looking through error message string?

you may enjoy addorupdate method. research first. have noted experts warning of on zealous use.

  context.set<tpoco>().addorupdate(poco); 

can still throw other ef\db exceptions. duplicate primary key should not 1 of them. other constraint issues before.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -