[EF Core] 善用 Entry 實現部份欄位更新

不需要將資料查詢回來, 就可以透過 Entry 更新完整或部份資料

環境

  • Asp Net Core 6
  • Ef Core 6
  • Local Db

事前資料

Id Name Email Phone
1 Test1 test1@test.com 123456789
2 Test2 test2@test.com 987654321

Core

1. 完整更新

var db = new MyDbContext(options);
var member = new Member
{
    Id = 2,
    Email = "",
    Name = "",
    Phone = "1122334455"
};
db.Members.Attach(member); // 追蹤物件, 標記state為 Unchanged
db.Members.Update(member); // 標記state為 Modified
db.SaveChanges(); // 更新完整資料

產生SQL

UPDATE [Member] SET [Email] = @p0, [Name] = @p1, [Phone] = @p2
WHERE [Id] = @p3;
-- @p0='', @p1='', @p2='11223344', @p3='2'

2. 部份更新

var db = new MyDbContext(options);
var member = new Member
{
    Id = 2,
    Email = "",
    Name = "",
    Phone = "1122334455"
};
db.Members.Attach(member);
db.Entry(member).Property(r => r.Phone).IsModified = true; // 想要更新的欄位
db.SaveChanges();

產生SQL

UPDATE [Member] SET [Phone] = @p0
WHERE [Id] = @p1;
-- @p0='1122334455', @p1='2'