Reputation: 99
im using poco code first . how do i get the last insert after savechanges() ?
thanks
Upvotes: 9
Views: 31394
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
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
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
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
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