简体   繁体   English

实体框架4获取插入记录的主键ID

[英]Entity Framework 4 getting primary key ID for inserted record

I am using the Entity Framework for inserting a row into my sql database. 我正在使用实体框架在我的sql数据库中插入一行。 If I was to be using a stored procedure then I would be able to return the primary key for the record which I had inserted. 如果要使用存储过程,则可以返回插入记录的主键。

Am I able to do return the PK for the last my last record inserted using the Entity Framework? 我是否可以使用实体框架返回最后插入的最后一条记录的PK?

插入实体后,应该已对其进行了更新,以便映射到数据库中主键的属性具有新的PK值。

Yes of course you can do this. 是的,您当然可以这样做。 See example: 参见示例:

int id = 0;

using (PC2Entities objectContext = new PC2Entities())
{
   objectContext.ClientContacts.AddObject(clientContact);
   objectContext.SaveChanges();
   id = clientContact.Id;

   transaction.Complete();
}

id is the PK. id是PK。

For Oracle.ManagedDataAccess.EntityFramework (version 6.121 or older) 对于Oracle.ManagedDataAccess.EntityFramework(版本6.121或更早版本)

If you still do not get the ID after inserting, then add this attribute on the primary key property. 如果插入后仍未获得ID,则在主键属性上添加此属性。

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
 public string ID { get; set; }

I had to do this, don't know why, may be because I am using oracle and entity framework is not happy about that. 我不得不这样做,不知道为什么,可能是因为我使用的是oracle,而实体框架对此并不满意。

Edit: I see this answer is down voted, and I know why, because the latest version of ODAP doesn't require you to put the [DatabaseGenerated(DatabaseGeneratedOption.Identity)]. 编辑:我看到这个答案被否决了,我知道为什么,因为ODAP的最新版本不需要您放入[DatabaseGenerated(DatabaseGeneratedOption.Identity)]。 But this was true for the older versions. 但这对于较旧的版本是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM