データベースとエンティティの設定
まず、EF6を用いたDBFirstアプローチで簡単なデモを作成します。従業員とその持ち物であるデバイスの関係を例にします。
-- データベース作成
CREATE DATABASE SampleDB;
GO
USE SampleDB;
GO
-- 従業員テーブル作成
CREATE TABLE [dbo].[Worker]
([worker_id] INT IDENTITY(1, 1) NOT NULL,
[worker_code] NVARCHAR(20),
[worker_name] NVARCHAR(20),
);
-- デバイステーブル作成
CREATE TABLE [dbo].[DeviceItem]
([device_id] INT IDENTITY(1, 1) NOT NULL,
[worker_ref_id] INT,
[device_name] NVARCHAR(20)
);
NuGetからEntityFrameworkパッケージをインストールし、接続文字列を設定ファイルに追加します:
<connectionStrings>
<add name="sampleConStr" connectionString="Data Source=192.168.0.106;Initial Catalog=SampleDB;User ID=user;Password=pass@123456" providerName="System.Data.SqlClient" />
</connectionStrings>
エンティティクラスを定義します:
[Table("Worker")]
public class WorkerEntity
{
public WorkerEntity()
{
DeviceItems = new HashSet<DeviceItemEntity>();
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int worker_id { get; set; }
[Column("worker_name")]
public string personName { get; set; }
public string worker_code { get; set; }
public virtual ICollection<DeviceItemEntity> DeviceItems { get; set; }
public void AddDevice(DeviceItemEntity entity)
{
this.DeviceItems.Add(entity);
}
public void RemoveDevice(DeviceItemEntity entity)
{
this.DeviceItems.Remove(entity);
}
}
[Table("DeviceItem")]
public class DeviceItemEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int device_id { get; set; }
public int worker_ref_id { get; set; }
public string device_name { get; set; }
}
DbContextを継承したコンテキストクラスを作成します:
public class WorkContext : DbContext
{
public WorkContext() : base("name=sampleConStr") {}
public virtual DbSet<WorkerEntity> Workers { get; set; }
}
クエリ操作
従業員およびデバイス情報の取得とSQLログ出力:
using (WorkContext context = new WorkContext())
{
context.Database.Log = sql => Console.WriteLine(sql);
var result = context.Workers.Find(1);
}
条件付き検索やJOINクエリも可能です:
public static List<WorkerDto> SearchWorkers()
{
using (WorkContext context = new WorkContext())
{
var query = from w in context.Workers
join d in context.DeviceItems on w.worker_id equals d.worker_ref_id
select new
{
Id = w.worker_id,
Name = w.personName,
DeviceName = d.device_name
};
// 結果の処理
}
return new List<WorkerDto>();
}
データ操作(CRUD)
新しい従業員データの追加:
static async Task AddWorkerAsync()
{
using (WorkContext context = new WorkContext())
{
WorkerEntity worker = new WorkerEntity();
worker.personName = "新規データ";
worker.worker_code = "W123";
worker.AddDevice(new DeviceItemEntity { device_name = "スマホ" });
context.Workers.Add(worker);
await context.SaveChangesAsync();
}
}
データ更新と削除も同様に実装できます:
static async Task UpdateWorkerAsync(int id)
{
using (WorkContext context = new WorkContext())
{
var worker = await context.Workers.FindAsync(id);
if (worker != null)
{
worker.personName = "更新後の名前";
await context.SaveChangesAsync();
}
}
}