2

EntityDataSource で DetailsView を使用し、EntityDataSource をエンティティ モデルに直接バインドしています。レコードが挿入された後に主キーの値を取得したい。どうすれば入手できますか

protected void detailsVewUser_ItemInserted(object sender, DetailsViewInsertedEventArgs e)

また

protected void EntityDataSource_Inserted(object sender, DetailsViewInsertedEventArgs e)
4

3 に答える 3

3

DetailsViewInsertedEventArgs には Values というプロパティがありますが、DetailsView から挿入する場合、通常、テキスト ボックスを介して主キーを提供しないため、新しく割り当てられた主キーはそこにありません。

代わりに EntityDataSource.Inserted イベントを使用できます。型キャストして主キー属性の値を取得できる Entity プロパティを持つ EntityDataSourceChangedEventArgs を渡します。たとえば、EntityDataSource を介して ObjectContext に挿入した Dependent というエンティティがある場合、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
}
于 2012-06-21T03:02:45.723 に答える
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 という名前の自動インクリメント スタイルの整数フィールドであると想定しています。ニーズに合わせて上記のコードを変更するか、質問がある場合はお知らせください。

于 2011-12-22T15:02:15.477 に答える
0

正確な構文はデータベースによって異なりますが、通常の方法は、SQL Server のように何かを行うことです。

Insert MyTable()...) Values(...) Scope_Identity を選択

したがって、リーダーまたはspを介して上記を実行するだけです(スカラーとして返すことができます)。

どのように、どこに戻すかはあなた次第ですが、viewmodel インスタンスを他のデータと共に渡す場合は、その id プロパティを設定するのが適切でクリーンです。

トリガーやデフォルトの制約などがある場合は、返された ID を使用してインスタンスをリロードすることをお勧めします。

于 2011-12-22T15:20:05.853 に答える