9
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LINQ to EntitiesでCRUDする方法についての備忘録

Last updated at Posted at 2018-03-26

業務でEntity Frameworkを使いました。
その際、SQLの構文とCRUDのメソッド名が違い、
少し悩んだのでメモ書。

また、IQuerable型でデータを扱わないと、SQLが発行されずに
LINQ to Objectsの扱いになる点にも注意。
膨大なデータのオブジェクトを扱ってしまうことになります。

SELECT
using (var context = new XXXXXContext())
{
    context.YYYYYs.Where(x => x.Id == 1);
    context.YYYYYs.Where(x => x.Name == "hogehoge").ToArray();
}
INSERT
using (var context = new XXXXXContext())
{
    // YYYYY Entity の Statesが
    // Unchanged状態→Added状態へ。
    context.YYYYYs.Add(
        new YYYYY()
        {
            id = 1,
            value= "hoge",
        });

    context.SaveChanges();
}
UPDATE
using (var context = new XXXXXContext())
{
    var yyyyy = context.YYYYYs.Single(x => x.Id == 1);
    yyyyy.Name = "Aiueo";
    context.SaveChanges();
}
SELECT→DELETE
using (var context = new XXXXXContext())
{
    var yyyyy = context.YYYYYs.Single(x => x.Id == 1);
    context.YYYYYs.Remove(yyyyy);
    context.SaveChanges();
}

Entity Frameworkは以下の状態を持っており、
SaveChanges()メソッドで更新系SQLを発行。

Unchanged: 追跡開始後に変更されていない状態
Added: 追加された状態。
Modified: 編集された状態。
Deleted: 削除された状態。
Detached: 追跡が開始されていない状態

参考

LINQ to Entitiesに関する私の勘違いを見直した話
Entity Framework

9
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?