.net 如何在实体框架中找到最后插入行的标识?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4068084/
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
How to find an identity of the last inserted row in Entity Framework?
提问by Vaibhav Jain
I am inserting data in multiple tables. I need to know the last inserted (auto-incremented) ID in the table. I need to use it as a Foriegn Key in some other table.
我在多个表中插入数据。我需要知道表中最后插入(自动递增)的 ID。我需要将它用作其他表中的外键。
In short I need alternative of @@Identityin T-Sql.
简而言之,我需要@@Identity在 T-Sql 中的替代品。
回答by Steven
Entity Framework will automatically load the last inserted id to populate the primary key column of the inserted entity:
Entity Framework 会自动加载最后插入的 id 来填充插入实体的主键列:
var customer = new Customer { Name = "Steven" };
context.AddObject(customer);
context.SaveChanges();
var id = customer.Id;
Note that the Idproperty only gets populated after calling SaveChanges()in case the StoreGeneratedPatternattribute is set to "Identity" or "Computed" for the auto-incremented ID column in the Storage part of the model.
请注意,该Id属性仅在调用后填充SaveChanges(),以防StoreGeneratedPattern模型的 Storage 部分中的自动递增 ID 列的属性设置为“身份”或“计算”。
回答by umer
Anyhow if you need the the id for some any other purpose ... calling EF Insert Method for some entity automatically returns the currently inserted row id ...
无论如何,如果您需要将 id 用于其他任何目的……为某些实体调用 EF 插入方法会自动返回当前插入的行 id ……
var rowId=db.Insert(Entity);

