Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ichiroku11/2e15c00e64d75ad509cf to your computer and use it in GitHub Desktop.
Save ichiroku11/2e15c00e64d75ad509cf to your computer and use it in GitHub Desktop.
Entity Frameworkでパラメータを渡してSQLを実行する
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
namespace ConsoleApp {
class Item {
public int Id { get; set; }
public string Name { get; set; }
}
class AppDbContext : DbContext {
private static readonly string _connectionString
= new SqlConnectionStringBuilder {
DataSource = ".",
IntegratedSecurity = true,
InitialCatalog = "Test"
}.ToString();
public AppDbContext()
: base(_connectionString) {
Database.Log = Console.Write; // ログ出力
}
}
class Program {
static void Main(string[] args) {
Database.SetInitializer(new NullDatabaseInitializer<AppDbContext>());
// パラメータなし
using (var context = new AppDbContext()) {
var item = context.Database.SqlQuery<Item>(@"select 1 as Id, N'Aaa' as Name;").First();
Console.WriteLine("{0}: {1}", item.Id, item.Name); // 1: Aaa
}
// パラメータを渡す
// @p0、@p1
using (var context = new AppDbContext()) {
var item = context.Database.SqlQuery<Item>(
@"select @p0 as Id, @p1 as Name;",
2, "Bbb").First();
Console.WriteLine("{0}: {1}", item.Id, item.Name); // 2: Bbb
}
// パラメータを渡す
// 名前付
using (var context = new AppDbContext()) {
var item = context.Database.SqlQuery<Item>(
@"select @id as Id, @name as Name;",
new SqlParameter("@id", 3), new SqlParameter("@name", "Ccc")).First();
Console.WriteLine("{0}: {1}", item.Id, item.Name); // 3: Ccc
}
// Dapper
using (var context = new AppDbContext()) {
var item = context.Database.Connection.Query<Item>(
@"select @id as Id, @name as Name;",
new { id = 4, name = "Ddd" }).First();
Console.WriteLine("{0}: {1}", item.Id, item.Name); // 4: Ddd
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment