Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Last active September 13, 2017 13:20
Show Gist options
  • Select an option

  • Save ichiroku11/a0b0d5eb0fd7756666cb85223cb7bce2 to your computer and use it in GitHub Desktop.

Select an option

Save ichiroku11/a0b0d5eb0fd7756666cb85223cb7bce2 to your computer and use it in GitHub Desktop.
EF Coreはじめました
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using Microsoft.EntityFrameworkCore;
namespace ConsoleApp {
public class AppDbContext : DbContext {
public DbSet<Monster> Monsters { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
// 接続文字列を指定する
var connectionString = new SqlConnectionStringBuilder {
DataSource = ".",
InitialCatalog = "Test",
IntegratedSecurity = true,
}.ToString();
optionsBuilder.UseSqlServer(connectionString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder) {
// テーブルにマッピングする
modelBuilder.Entity<Monster>().ToTable("Monster");
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp {
// モンスター
public class Monster {
public int Id { get; set; }
public string Name { get; set; }
}
}
drop table if exists dbo.Monster;
-- モンスター
create table dbo.Monster(
Id int,
Name nvarchar(20),
constraint PK_Monster primary key(Id)
);
insert into dbo.Monster(Id, Name)
output inserted.*
values
(1, N'スライム'),
(2, N'ドラキー');
/*
Id Name
----------- --------------------
1 スライム
2 ドラキー
*/
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp {
class Program {
static void Main(string[] args) {
using(var dbContext = new AppDbContext()) {
// データを取得
var monsters = dbContext.Monsters.ToList();
foreach (var monster in monsters) {
Console.WriteLine($"#{monster.Id} {monster.Name}");
}
//#1 スライム
//#2 ドラキー
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment