LoginSignup
0
2

More than 5 years have passed since last update.

C# Entity SCOPE_IDENTITY()をExecuteSqlCommandで取得する方法

Posted at

C# Entity ExecuteSqlCommandでSCOPE_IDENTITY()を取得する

課題

SQLServerでIDなどIdentityを設定してあるテーブルに、Insert時に採番されるIDをInsertと同時に取得しようとすると、SCOPE_IDENTITY()を使用すると思いますが、
ExecuteScalar()などを利用すると、戻り値で採番されたIDを受け取れるがEntityのExecuteSqlCommandだと戻り値では受け取れない。

パラメータでの受け取り

ExecuteSqlCommandにパラメータを渡し受け取る方法だと実現が可能。

サンプル

sample.cs
string sql = "Insert ・・・・・・・・
values
・・・・・・・・);
Select SCOPE_IDENTITY()";

var a = Database.ExecuteSqlCommand(sql);

この時のaにSCOPE_IDENTITYが入ってこない。ま~当たり前なんですが・・・

これを、Parameterで受け取るようにすると、

sample.cs
string sql = "Insert ・・・・・・・・
values
・・・・・・・・);
Select @MyID = SCOPE_IDENTITY()";

SqlParameter parm = new SqlParameter() {
 ParameterName = "@MyID",
 SqlDbType = System.Data.SqlDbType.int,
 Direction = System.Data.ParameterDirection.Output
};

Database.ExecuteSqlCommand(sql, param);
int IdentityID = (int)param.Value;

これで取得することができます。
サンプルとして。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2