【问题标题】:Get primary key column value after inserting record using DetailsView and EntityDataSource使用 DetailsView 和 EntityDataSource 插入记录后获取主键列值
【发布时间】:2011-12-22 14:41:28
【问题描述】:
我将 DetailsView 与 EntityDataSource 一起使用,并将 EntityDataSource 直接与实体模型绑定。
我想在插入记录后获取主键值。我怎样才能在
protected void detailsVewUser_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
或
protected void EntityDataSource_Inserted(object sender, DetailsViewInsertedEventArgs e)
【问题讨论】:
标签:
asp.net
entity-framework
detailsview
entitydatasource
【解决方案1】:
DetailsViewInsertedEventArgs 有一个叫做 Values 的属性,但是当你从 DetailsView 插入时,通常不会通过文本框提供主键,因此新分配的主键不会在那里。
您可以改用 EntityDataSource.Inserted 事件。它传递 EntityDataSourceChangedEventArgs ,它具有一个 Entity 属性,您可以对其进行类型转换,然后获取主键属性的值。例如,如果我刚刚通过 EntityDataSource 将一个名为 Dependent 的实体插入到我的 ObjectContext 中,那么 EntityDataSource 的事件处理程序可能如下所示:
protected override dependentInformationDataSource_OnInserted(object sender, EntityDataSourceChangedEventArgs e )
{
// let's say my Dependent entity's primary key is called DependentKey
int newPrimaryKey = ((Dependent)e.Entity).DependentKey;
// do something with newPrimaryKey
}
【解决方案2】:
确切的语法取决于数据库,但通常的方法是像在 sql server 中那样做一些事情
插入 MyTable()...) 值(...)
选择Scope_Identity
所以只需通过阅读器或 sp 执行上述操作(然后您可以将其作为标量返回)。
如何以及在何处将其传回由您自己决定,但如果您使用其他数据传入 viewmodel 实例,则填充它的 id 属性既好又干净。
如果您有触发器和默认约束等,使用传回的身份重新加载实例会更好。
【解决方案3】:
您可以直接从数据库中提取新 ID(我假设是 SQL,但无论您使用的是哪个数据库),因为它已被插入:
// an int to store your newly inserted ID
int newID = 0;
// a string containing a query that gets your latest, inserted record.
// Modify to your specific needs =)
string newIDQuery = "SELECT TOP 1 ID FROM tableName ORDER BY ID DESC;";
SqlCommand getNewIdCommand = New SqlCommand(newIDQuery, New SqlConnection("You Connection String"));
getNewIdCommand.Connection.Open(); // open the SQL connection
newID = getNewIdCommand.ExecuteScalar(); // this loads the int variable with the newest ID
getNewIdCommand.Connection.Close(); // close the SQL connection
注意:此示例假定您的主键列是一个名为 ID 的自动增量式整数字段。修改上面的代码以满足您的需要,或者如果您有任何问题,请告诉我!