EntityFrameworkCore 扩展类 AddOrUpdate
现在项目用了前后端分离,所以每次提供接口的时候都是
Edit一个api接口,然后Add一个api接口,
然后做了一个后端项目突然想起来EF之前好像有个扩展类 AddOrUpdate,
于是网上找了下:代码如下
1 public static class ContextExtensions 2 { 3 public static void AddOrUpdate(this DbContext ctx, object entity) 4 { 5 var entry = ctx.Entry(entity); 6 switch (entry.State) 7 { 8 case EntityState.Detached: 9 ctx.Add(entity); 10 break; 11 case EntityState.Modified: 12 ctx.Update(entity); 13 break; 14 case EntityState.Added: 15 ctx.Add(entity); 16 break; 17 case EntityState.Unchanged: 18 //item already in db no need to do anything 19 break; 20 21 default: 22 throw new ArgumentOutOfRangeException(); 23 } 24 } 25 }
参考:
https://www.michaelgmccarthy.com/2016/08/24/entity-framework-addorupdate-is-a-destructive-operation/
https://docs.microsoft.com/zh-cn/ef/ef6/saving/change-tracking/entity-state