插入后在实体框架中获取记录ID

时间:2013-06-06 06:06:12

标签: asp.net entity-framework-4.1 detailsview

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

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

我正在使用DetailsView和EntityDataSource并将EntityDataSource直接与实体模型绑定,所以我不是要创建插入数据的对象。

4 个答案:

答案 0 :(得分:42)

在致电_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;

答案 1 :(得分:5)

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

MyObject.Id会为您提供新的ID

答案 2 :(得分: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"

答案 3 :(得分: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