0

With ADO.NET and stored procedures, it's simple to return Scope_Identity() as an output parameter from SQL Server so that you can immediate perform a get and get the same row/object you just inserted. I'm a little confused on how to properly achieve this with EF?

I'm using MVC4, EF5 (Code first/Fluent API), and a Repository Pattern in a Service Layer for CRUD and business logic so that the Controller doesn't have to deal with EF any data access. An Action in my controller passes a ViewModel to the service layer for insert, but naturally has no ID yet. The Service Layer converts the view model to a Domain Entity model and inserts it. Now I want to return the same view model back to my view, but how can I be sure it's the same object without an ID? Seems like there should be an obvious solution without having to resort to timedatestamps or guids.

Sorry if this is basic but I haven't been able to find an answer to this.

tereško
  • 58,060
  • 25
  • 98
  • 150
JM.
  • 678
  • 12
  • 23
  • 1
    http://stackoverflow.com/questions/5212751/how-can-i-get-id-of-inserted-entity-in-entity-framework – AaronLS May 20 '13 at 23:44
  • http://stackoverflow.com/questions/6466224/entity-framework-4-getting-primary-key-id-for-inserted-record – AaronLS May 20 '13 at 23:45
  • http://stackoverflow.com/questions/8435462/get-auto-identity-key-after-insert-via-ef – AaronLS May 20 '13 at 23:46
  • Not sure what you mean by "how can I be sure it's the same object?". If you pass an object in, and your code returns the same object to the caller, I can't understand how it wouldn't be the same object and how you couldn't be sure it was the same object. Simple solution, don't pass a different object back and you can be sure it's the same. – Erik Funkenbusch May 21 '13 at 01:34
  • @JM. Can't you change the service layer which gets a `ViewModel` and converts it to a `Domain Entity` to return the `Domain Entity` object that was inserted in database? – Catalin May 21 '13 at 07:55
  • 1
    @AaronLS - I know this old but I wanted to say thx. Wow I suck at search. Apparently as bad as you are good. Apologies and tyvm for the links. Good to know it's auto-updated. Thought I would have to perform an insert followed by a get. – JM. Jul 17 '13 at 04:02

1 Answers1

1

When an object is inserted by Entity Framework, the INSERT query it is immediately followed by a SELECT to read any database generated values back into the object. This includes the Id value (if it is an identity column) and any computed columns.

So after the insert you can be 100% sure that the object is in the state in which it was inserted and also contains any database generated values.

If you want to be 200% sure you can do

context.Entry(myNewObject).Reload();

Maybe in a situation with high concurrency this could be useful when you know that there is some time between the insert and the actual post back to the UI but otherwise it's really not necessary.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291