我在我的MVC
应用程序上使用async/await
,当调用context.SaveChangesAsync()
(它甚至发生在不使用异步时)时,我得到一个DataException
。更新抛出DataException
我实施的工作单元模式发现here我试过了一切,改变代码,使用同步代替,评论调用线等我没有想法。我的实体不会更新。但他们确实得到了创造性思维。
这里是我的一段代码:
// Inside POST EDIT
try {
if (ModelState.IsValid) {
unitOfWork.StudentRepository.Update(student);
await unitOfWork.SaveAsync();
return RedirectToAction("Index");
}
} catch (DataException) {
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persist see your system administrator");
}
// Inside Repository -- It's a generic type defined as
// public class GenericRepository<TEntity> : IGenericRepository<TEntity>
// where TEntity : class { .......
public GenericRepository(SchoolContext context) {
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual void Update(TEntity entityToUpdate) {
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
// Inside UnitOfWork
public Task<int> SaveAsync() {
return context != null ? context.SaveChangesAsync() : Task.FromResult<int>(1);
}
更新:做了许多研究后,我发现人们使用剪断这样的代码:
public void ApplyStateChanges()
{
foreach (var dbEntityEntry in ChangeTracker.Entries())
{
var entityState = dbEntityEntry.Entity as EntityBase;
if (entityState == null)
throw new InvalidCastException("All entites must implement the IObjectState interface, " +
"this interface must be implemented so each entites state can explicitely determined when updating graphs.");
dbEntityEntry.State = StateHelper.ConvertState(entityState.State);
}
}
和SaveChangesAsync()
之前调用它,这与我面临的问题有什么关系?
更新2:这是我点击Copy exception detail to the clipboard时得到的结果。
我试图改变的代码使用TryToUpdateModel()
,并没有抛出异常,但数据不更新反正
发布完整的例外和堆栈跟踪! – 2015-02-06 22:06:59
请发布来自异常和它的内部异常(如果存在)的消息。错误*可能与你的代码无关,并且与没有找到的数据库或表与对象之间的列不匹配有关。 – 2015-02-06 22:21:36
我从'DataException'发布了一个链接到我的堆栈跟踪,希望这可以帮助我解决问题 – 2015-02-06 22:30:41