EntityFramework - SQL実行

EntityFrameworkでSQLを直接実行する方法

  • selectの場合:SqlQuery
  • insert,update,deleteの場合:ExecuteSqlCommand

SQL結果データ

public class SqlResultData
{
  string title { get; set; }
  string pub_id { get; set; }
  string pub_name { get; set; }
}

SQL実行(外部結合、パラメータなし)

static void Test3()
{
  using (pubsEntities db = new pubsEntities())
  {
    var q = @"select t.title,t.pub_id, p.pub_name from titles as t left outer join publishers as p on t.pub_id = p.pub_id";
    var r = db.Database.SqlQuery<SqlResultData>(q);

    foreach (var item in r)
    {
      Console.WriteLine("{0}:{1}:{2}", item.title, item.pub_id, item.pub_name);
    }
  }
}

SQL実行(外部結合、パラメータあり)

public static void Test4()
{
  using (pubsEntities db = new pubsEntities())
  {
    var q = @"select t.title,t.pub_id, p.pub_name from titles as t left outer join publishers as p on t.pub_id = p.pub_id where t.pub_id=@pub_id";
    var param_pub_id = new SqlParameter("@pub_id", 1389);
    var r = db.Database.SqlQuery<SqlResultData>(q, param_pub_id);

    foreach (var item in r)
    {
      Console.WriteLine("{0}:{1}:{2}", item.title, item.pub_id, item.pub_name);
    }
  }
}