2015-02-06 52 views
1

我在我的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(),并没有抛出异常,但数据不更新反正

+0

发布完整的例外和堆栈跟踪! – 2015-02-06 22:06:59

+0

请发布来自异常和它的内部异常(如果存在)的消息。错误*可能与你的代码无关,并且与没有找到的数据库或表与对象之间的列不匹配有关。 – 2015-02-06 22:21:36

+0

我从'DataException'发布了一个链接到我的堆栈跟踪,希望这可以帮助我解决问题 – 2015-02-06 22:30:41

回答

0

我真的希望没有其他人都会经历这个。所以,问题是以下几点:

我在DbContext,这样我可以做到在每一个实体的时间戳与CreatedDateUpdatedDate性质重写SaveChanges()SaveChangesAsync()通过ITimestamp

更新您不要修改CreatedDate的时候,因为它得到一个null值,C#似乎并不为允许空上DateTime

所以为了解决这个问题,我marketd它作为未修饰像这里面我重写保存方法:

if (entry.State == EntityState.Modified) { 
    Entry(entry.Entity as ITimestamp).Property(e => e.CreatedDate).IsModified = false; 
}