2013-06-06 89 views
18

我正在使用实体框架开发ASP.net应用程序。我正在使用DetailsView将数据插入数据库。有一个表为Client,其主键为client_idclient_id是数据库自动生成的。在将记录插入Client表后,我需要自动生成client_id,并将其分配给隐藏字段以供将来使用。插入后在实体框架中获取记录ID

我搜索了这个,我发现了很多解决方案。但我不知道如何使用它们,因为我是新来的asp.net。我发现在调用SaveChanges()之后,Entity Framework会自动用db生成的值填充业务对象。我的问题是我应该在我的部分课程中把它称为什么?什么是事件?

我使用DetailsView与EntityDataSource和EntityDataSource直接与实体模型绑定,所以我不创建对象来插入数据。

+0

可能重复的[我如何获得在实体框架中插入实体的Id?](http://stackoverflow.com/questions/5212751/how-cani-i- get-id-of-inserted-entity-in-entity-framework) –

+1

@Michael Freidgeim它不是重复的,因为Bishan希望使用EntityDataSource,并且问题和答案与EntityDataSource无关。 –

回答

3

这就是我要找的。

部分类

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" 
+1

谢谢!这正是我所期待的! –

5

插入实体后,应更新它,以便映射到数据库中主键的属性具有新的PK值。

MyObject.Id会给你新的ID

+0

我正在使用DetailsView和EntityDataSource,并直接使用实体模型绑定EntityDataSource。所以我不创建对象来插入数据。 – Bishan

37

继呼叫_dbContext.SaveChanges(),该实体将自动与新的标识字段的值更新。

下面的代码假定您的实体框架的实体容器名称是MyEntities,和你的数据库的客户表至少具有以下两个领域:

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; 
+0

我使用'DetailsView'与'EntityDataSource'并直接使用Entity Model绑定'EntityDataSource'。所以我不创建对象来插入数据。 – Bishan

0

谢谢,我了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