因为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都没问题.因为上面已经把状态给同步了.