SQL asp mvc 从 savechanges() 获取最后一个插入 id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5103792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
asp mvc get last insert id from savechanges()
提问by colorblack04
im using poco code first . how do i get the last insert after savechanges() ?
我首先使用 poco 代码。我如何在 savechanges() 之后获得最后一次插入?
thanks
谢谢
回答by L.A.
I resolve that problem in such way:
我以这种方式解决了这个问题:
with Max() - you can get last id from table
使用 Max() - 您可以从表中获取最后一个 ID
db.Products.Add(product);
db.SaveChanges();
int lastProductId = db.Products.Max(item => item.ProductId);
ProductId is Key() and increment
ProductId 是 Key() 和增量
回答by user1442894
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;
回答by J. Tihon
After you've saved an entity in the context (SaveChanges()). The ID property on the poco itself should be set by the entity framework.
在上下文中保存实体后 (SaveChanges())。poco 本身的 ID 属性应该由实体框架设置。
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.
如果您确实需要有关已修改实体的更多信息,可以在实体框架的 ObjectContext 提供的 ObjectStateManager 中查找它们。
回答by Ruan
var newProduct = db.Product.Add(model);
db.SaveChanges();
var productId = model.Id;
It automatically adds it to the object you are saving
它会自动将其添加到您正在保存的对象中
回答by Gautam Sharma
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