AddOrUpdate

Topics: EF Runtime
Dec 15, 2012 at 7:02 AM
I've recently encountered this problem where I need to add an entity or update (increment a property) if it already exists. This has to work with concurrency. Unfortunately there is no way to do this in a straightforward way in EF. I can try an insert, submit changes within a try/catch. If it failed, i need to query the entity first, update it then submit changes. Whew! That's a lot of code to do something very simple (and it actually won't work if I have multiple clients trying the same thing at once). I ended up executing the following SQL query directly: UPDATE xxx SET Value = Value + 1 WHERE yyy IF @@ROWCOUNT=0 INSERT INTO xxx VALUES (...); I'm not sure if this would be possible given how EF works but I'd like to do something like this: xxx.AddOrUpdate(new Entity(), e => e.Value++); Thoughts?
Dec 18, 2012 at 8:51 AM

+1. Agree. Especially given that this can emit different code (MERGE statement instead of insert/update combo). Whe whole SQL side of EF is still quite - simple.