使用DetailsView和EntityDataSource插入记录后获取主键列值

时间:2011-12-22 14:41:29

标签: asp.net entity-framework detailsview entitydatasource

我正在使用DetailsView和EntityDataSource,并将EntityDataSource直接与实体模型绑定。 我希望在插入记录后获取主键值。我怎样才能在

中得到它
protected void detailsVewUser_ItemInserted(object sender, DetailsViewInsertedEventArgs e)

protected void EntityDataSource_Inserted(object sender, DetailsViewInsertedEventArgs e)

3 个答案:

答案 0 :(得分:2)

DetailsViewInsertedEventArgs有一个名为Values的属性,但是当你从DetailsView插入时,通常不会通过文本框提供主键,因此新分配的主键不在那里。

您可以使用EntityDataSource.Inserted事件。它传递EntityDataSourceChangedEventArgs,它具有Entity属性,您可以键入 - 然后获取主键属性的值。例如,如果我有一个名为Dependent的实体,我刚刚通过EntityDataSource插入到我的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
}

答案 1 :(得分:0)

您可以直接从数据库中提取新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的自动增量样式整数字段。修改上述代码以满足您的需求,或者如果您有任何疑问,请告诉我们!

答案 2 :(得分:0)

确切的语法取决于数据库,但通常的方法是在sql server中做somne​​thing

插入MyTable()...)值(...) 选择Scope_Identity

所以只需通过阅读器或sp执行上述操作(您可以将其作为标量返回)。

传递它的方式和位置取决于您,但如果您使用其他数据传入viewmodel实例,则填充它的id属性非常简洁。

如果你有触发器和默认约束等,那么使用传回的身份重新加载实例会更好。