简体   繁体   中英

Entity Framework 4 getting primary key ID for inserted record

I am using the Entity Framework for inserting a row into my sql database. 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值。

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.

For Oracle.ManagedDataAccess.EntityFramework (version 6.121 or older)

If you still do not get the ID after inserting, then add this attribute on the primary key property.

[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.

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)]. But this was true for the older versions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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