Entity Frameworkでストアドプロシージャの戻り値を取得する

Entity Frameworkを使っているときに、ストアドプロシージャからの戻り値を取得する方法を簡単にまとめてみた。

Entity Frameworkを使って、ストアドプロシージャの戻り値を取得する方法の情報が少なかったのでサンプルレベルで書いてみた。

まず、SQL Serverでストアドプロシージャを作成する。今回は引数の値をそのまま返す簡単なものとした。「Test」という名前のデータベースを作成して、そこにストアドプロシージャを作成する。

create procedure sp_ReturnTestID
	@TestID int
as

return @TestID

SQL Serverでの作業が終わったら、次にVisual Studioでの作業に移る。Visual Studio 2010でADO.NET Entity Data Modelを追加し、モデルブラウザーのストアドプロシージャから関数インポートを行う。

関数インポートのときは、そのままの設定で大丈夫だ。

ここまで終了したらコードの作成に移る。

using System;
using System.Data.EntityClient;

namespace GetReturnValueProcedure
{
    class Program
    {
        static void Main(string[] args)
        {
            int testID = 3;

            try
            {
                using (var entities = new TestEntities())
                {
                    entities.Connection.Open();
                    using (var command = entities.Connection.CreateCommand())
                    {
                        command.CommandText = "TestEntities.sp_ReturnTestID";
                        command.CommandType = System.Data.CommandType.StoredProcedure;
                        command.Parameters.Add(new EntityParameter() { ParameterName = "TestID", Value = testID, DbType = System.Data.DbType.Int32 });
                        command.Parameters.Add(new EntityParameter() { ParameterName = "ReturnValue", Direction = System.Data.ParameterDirection.ReturnValue, DbType = System.Data.DbType.Int32 });
                        command.ExecuteNonQuery();
                        var result = command.Parameters["ReturnValue"].Value;
                        Console.WriteLine("Return Value: {0}", result);
                        Console.Read();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

これでOUTPUTパラメーターを指定しなくてもストアドプロシージャの戻り値を取得することができる。

Follow me!

Feedlyで新着記事をチェックしよう!

Feedlyでフォローしておけば、新着記事をチェックすることができます。ぜひ、この機会にFeedlyに追加しておきましょう。