Last active
August 29, 2015 14:02
-
-
Save ichiroku11/2e15c00e64d75ad509cf to your computer and use it in GitHub Desktop.
Entity Frameworkでパラメータを渡してSQLを実行する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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