2011-12-22 90 views
1

我将DetailsView与EntityDataSource结合使用,并将EntityDataSource直接与Entity Model绑定。 我想在插入记录后获取主键值。我怎么能现在,它得到它无论是在使用DetailsView和EntityDataSource插入记录后获取主键列值

protected void detailsVewUser_ItemInserted(object sender, DetailsViewInsertedEventArgs e) 

protected void EntityDataSource_Inserted(object sender, DetailsViewInsertedEventArgs e) 
+0

有你看了[EntityDataSourceChangedEventArgs(HTTP:/ /msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.entitydatasourcechangedeventargs.aspx)属性?这是'_Inserted'方法的一个参数,可能有你在找的东西。 – jadarnel27 2011-12-22 15:11:18

回答

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自动递增式整场。修改上面的代码以满足您的需求,或者让我知道您是否有问题!

0

确切语法取决于数据库,但通常的方法是在SQL Server

插入MyTable的()...)值做somne​​thing像(...) 选择SCOPE_IDENTITY

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

如何以及在何处传回它取决于您,但是如果您将视图模型实例与其他数据一起传递,那么填充它的id属性非常干净。

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

2

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

您可以改为使用EntityDataSource.Inserted事件。它传递EntityDataSourceChangedEventArgs,它具有一个Entity属性,您可以对其进行类型转换,然后获取主键属性的值。举例来说,如果我有一个实体,称为依赖的,我只是插入通过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 
} 
相关问题