colorblack04
colorblack04

Reputation: 99

asp mvc get last insert id from savechanges()

im using poco code first . how do i get the last insert after savechanges() ?

thanks

Upvotes: 9

Views: 31394

Answers (5)

Gautam Sharma
Gautam Sharma

Reputation: 33

Refer to the following example -

db.Hotels.Add(hotels);
                db.SaveChanges();
                var id = hotels.Id;

It worked for me.

Source - https://dzone.com/articles/how-return-id-field-after

Upvotes: 0

Ruan
Ruan

Reputation: 4283

var newProduct = db.Product.Add(model);
db.SaveChanges();
var productId = model.Id;

It automatically adds it to the object you are saving

Upvotes: 4

user1442894
user1442894

Reputation: 170

register = db.registers.CreateObject();
register.id = 0;
register.customer = h.customer;
register.employee = employee_created;
register.created = DateTime.Now;
db.registers.AddObject(register);
db.SaveChanges();

//You can get the ID here
int last_insert_id = register.id;

Upvotes: 11

L.A.
L.A.

Reputation: 719

I resolve that problem in such way:

with Max() - you can get last id from table

db.Products.Add(product);
db.SaveChanges();
int lastProductId = db.Products.Max(item => item.ProductId);

ProductId is Key() and increment

Upvotes: 16

J. Tihon
J. Tihon

Reputation: 4459

After you've saved an entity in the context (SaveChanges()). The ID property on the poco itself should be set by the entity framework.

If you actually want more information about the modified entities, you can look for them in the ObjectStateManager provided by the Entity Framework's ObjectContext.

Upvotes: 8

Related Questions