因为4.x/5.0的context都采用了继承DbContext,但DbContext不提供修改字段状态的相关操作方法,可是实现了IObjectContextAdapter接口,我们可以从这里拿到ObjectContext,这样一切都好办了.我们可以如下操作
public int Update(E entity, string[] propertys) { int changeCount = 0; using(TransactionScope transaction = new TransactionScope (TransactionScopeOption.Required)) { using (YzOASysEntities context = new YzOASysEntities()) { context.Set<E>().Attach(entity); IObjectContextAdapter objectContextAdatper = context; ObjectContext objectContext = objectContextAdatper.ObjectContext; ObjectStateEntry ose = objectContext.ObjectStateManager.GetObjectStateEntry(entity); foreach (string property in propertys) { ose.SetModifiedProperty(property); } if (context.Entry<E>(entity).State == EntityState.Unchanged) context.Entry<E>(entity).State = EntityState.Modified; changeCount = context.SaveChanges(); if (changeCount > 0) transaction.Complete(); } } return changeCount; }
其实设不设置State是Modified都没问题.因为上面已经把状态给同步了.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步