[英]Get Record ID in Entity Framework after insert
我正在使用實體框架開發一個 ASP.net 應用程序。 我正在使用DetailsView
將數據插入數據庫。 有一個表作為Client
,它的主鍵是client_id
。 client_id
由數據庫自動生成。 在將記錄插入Client
表后,我需要獲取自動生成的client_id
並將其分配給隱藏字段以供將來使用。
我對此進行了搜索,並找到了很多解決方案。 但我不知道如何使用它們,因為我是 asp.net 的新手。 我發現 Entity Framework 在調用SaveChanges()
后會自動使用 db 生成的值填充業務對象。 我的問題是我應該在我的部分課程中把它叫做什么? 什么是事件?
我將 DetailsView 與 EntityDataSource 一起使用,並將 EntityDataSource 直接與 Entity Model 綁定,因此我沒有創建對象來插入數據。
在調用_dbContext.SaveChanges()
之后,實體將自動更新為其新的身份字段值。
以下代碼假定您的 Entity Framework 實體容器名稱為 MyEntities,並且您的數據庫的 Client 表至少具有以下兩個字段:
client_id int identity
client_name varchar(25)
您的代碼可能如下所示:
// Establish DbContext
private readonly MyEntities _dbContext = new MyEntities();
// Create new client table entity and initialize its properties
var clientEntity = new Client { client_name="MyCo" };
// Add it to the ORM's collection of Client entities
_dbContext.Clients.Add(clientEntity);
// Save the new entity to the database
_dbContext.SaveChanges();
// Return the identity field from the existing entity,
// which was updated when the record was saved to the database
return clientEntity.client_id;
插入實體后,應該更新它,以便映射到數據庫中主鍵的屬性具有新的 PK 值。
就像MyObject.Id
會給你新的 ID
這就是我要找的。
在部分班級
protected void clientDataSource_OnInserted(object sender, EntityDataSourceChangedEventArgs e )
{
int newPrimaryKey = ((Client)e.Entity).ClientId;
Debug.WriteLine(" Client ID is " + newPrimaryKey);
}
並在 aspx 頁面的EntityDataSource
中添加以下行。
OnInserted="clientDataSource_OnInserted"
謝謝,我花了 3 天時間搜索和搜索復雜的結果,但這個解決方案很棒! 這是在 vb.net 中:
Protected Sub dvArticulos_ItemInserted(sender As Object, e As EntityDataSourceChangedEventArgs) Handles EntityDataSource1.Inserted
Dim last_Serie As Long = DirectCast(e.Entity, articulos).Serie
Session("Articulo") = last_Serie
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.