Tech Days フォローアップ(その6)  ADO.NET Entity Framework ストアドプロシージャのプログラミング Entity Client編

みなさん、こんにちは。今日はADO.NET Entity Frameworkにおけるストアドプロシージャの利用方法についてご紹介します。今日はEntity Client編です。次回はObject Services編をご紹介します。

Entity Clientプログラミングの詳細は下記のURLをご参照ください。

https://msdn.microsoft.com/ja-jp/library/system.data.entityclient.aspx

ここでは簡単にご説明します。まずキーになるクラスは以下の3つになります。

・EntityConnection

・EntityCommand

・EntityParameter

これらのクラスを利用してプログラミングすると下記のようになります。

 EntityConnection entityConnection = (EntityConnection)context.Connection;

 EntityCommand entityCommand = entityConnection.CreateCommand();

 entityCommand.CommandType = System.Data.CommandType.StoredProcedure;

  // 事前にモデルブラウザから「関数インポートの作成」を実行

 entityCommand.CommandText = string.Format("{0}.{1}", context.DefaultContainerName, "InsertDrinkProduct"); ;

 EntityParameter ep1 = new EntityParameter();

 ep1.ParameterName = @"productid";

 ep1.DbType = System.Data.DbType.Int32;

 ep1.Value = drinkproduct.ProductID;

 entityCommand.Parameters.Add(ep1);

 EntityParameter ep2 = new EntityParameter();

 ep2.ParameterName = @"productname";

 ep2.DbType = System.Data.DbType.String;

 ep2.Value = drinkproduct.ProductName;

 entityCommand.Parameters.Add(ep2);

 EntityParameter ep3 = new EntityParameter();

 ep3.ParameterName = @"size";

 ep3.DbType = System.Data.DbType.Int32;

 ep3.Value = drinkproduct.Size;

 entityCommand.Parameters.Add(ep3);

 entityConnection.Open();

 entityCommand.ExecuteScalar();

 entityConnection.Close();

もう少しキレイに実装したいのであれば下記をご参考にしてください。

https://grifftownsend.blogspot.com/2008/08/small-extension-to-entity-framework.html