不需要將資料查詢回來, 就可以透過 Entry 更新完整或部份資料
環境
- Asp Net Core 6
- Ef Core 6
- Local Db
事前資料
Core
1. 完整更新
var db = new MyDbContext(options);
var member = new Member
{
Id = 2,
Email = "",
Name = "",
Phone = "1122334455"
};
db.Members.Attach(member);
db.Members.Update(member);
db.SaveChanges();
產生SQL
UPDATE [Member] SET [Email] = @p0, [Name] = @p1, [Phone] = @p2
WHERE [Id] = @p3;
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;
環境
事前資料
Core
1. 完整更新
產生SQL
UPDATE [Member] SET [Email] = @p0, [Name] = @p1, [Phone] = @p2 WHERE [Id] = @p3; -- @p0='', @p1='', @p2='11223344', @p3='2'
2. 部份更新
產生SQL
UPDATE [Member] SET [Phone] = @p0 WHERE [Id] = @p1; -- @p0='1122334455', @p1='2'