Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Newly generated ID (i.e. scopeIdentity) in Entity FrameWork

I am added a record in my table e.g. Orders. After adding the record i want to get the newly generated ID of the inserted record. Like SCOPEIDENTY in SQL.

But how can i do this in Entity Framework.

like image 564
Waheed Avatar asked Apr 20 '10 13:04

Waheed


People also ask

How do I get an ID after inserting EF core?

EF execute each INSERT command followed by SELECT scope_identity() statement. SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. The above example will execute the following SQL in the database. WHERE @@ROWCOUNT = 1 AND [StudentID] = scope_identity();

How do I add a new record in Entity Framework?

Use the DbSet. Add method to add a new entity to a context (instance of DbContext ), which will insert a new record in the database when you call the SaveChanges() method.

How do I use Find in Entity Framework?

The Find method on DbSet uses the primary key value to attempt to find an entity tracked by the context. If the entity is not found in the context then a query will be sent to the database to find the entity there. Null is returned if the entity is not found in the context or in the database.


1 Answers

After you saved your changes, your entity object should reflect the newly generated ID automagically. It's one of the many great things about the Entity Framework. :-)

like image 83
Prutswonder Avatar answered Sep 28 '22 02:09

Prutswonder