using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DbConnection.Models;
using Dapper;
using System;
using System.Data;
using System.Data.EntityClient;
namespace DbConnection.Controllers
{
public class SampleController : ApiController
{
//ログのインスタンス
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
public IHttpActionResult Get()
{
//name = 接続文字列 ※Web.configのconnectionStringsディレクティブに「sqlserver」という文字列で設定済み
using (EntityConnection connection = new EntityConnection("name = sqlserver"))
{
//DB接続
connection.Open();
using (EntityCommand cmd = connection.CreateCommand())
{
try
{
//実行するプロシージャ名
cmd.CommandText = "sqlserver.sp_test";
//コマンドタイプをプロシージャに設定
cmd.CommandType = CommandType.StoredProcedure;
//パラメーター1のインスタンス
EntityParameter param1 = new EntityParameter();
//パラメーター名
param1.ParameterName = "id";
//パラメーター値
param1.Value = "10";
//パラメーター2のインスタンス
EntityParameter param2 = new EntityParameter();
//パラメーター名
param2.ParameterName = "name";
//パラメーター値
param2.Value = "Add_Procedure";
//プロシージャにパラメーターをセット
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param2);
//プロシージャ実行
using (EntityDataReader execute = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
logger.Info("param1: " + param1.ParameterName + param1.Value);
logger.Info("param2: " + param2.ParameterName + param2.Value);
}
}
catch (Exception e)
{
logger.Error(e);
return BadRequest();
}
}
}
return Ok();
}
}
}