Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp mvc get last insert id from savechanges()

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

thanks

like image 859
colorblack04 Avatar asked Feb 24 '11 11:02

colorblack04


2 Answers

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

It automatically adds it to the object you are saving

like image 134
Ruan Avatar answered Sep 28 '22 06:09

Ruan


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

like image 24
L.A. Avatar answered Sep 28 '22 06:09

L.A.