/// <summary> /// 将在此上下文中所做的所有更改异步保存到基础数据库。<paramref name="validateOnSaveEnabled"/> 参数指示在调用 SaveChanges() 时,是否应自动验证所跟踪的实体。 /// </summary> /// <param name="context">表示当前数据库访问上下文 <see cref="System.Data.Entity.DbContext"/> 对象。</param> /// <param name="cancellationToken">等待任务完成期间要观察的 <see cref="CancellationToken"/>。</param> /// <param name="validateOnSaveEnabled">指示在调用 SaveChanges() 时,是否应自动验证所跟踪的实体。</param> /// <returns>表示异步保存操作的任务。任务结果包含已写入基础数据库的对象数目。</returns> public static Task <int> SaveChangesAsync(this System.Data.Entity.DbContext context, CancellationToken cancellationToken, bool validateOnSaveEnabled) { bool enabled = context.Configuration.ValidateOnSaveEnabled; context.Configuration.ValidateOnSaveEnabled = validateOnSaveEnabled; try { context.Configuration.ValidateOnSaveEnabled = validateOnSaveEnabled; return(context.SaveChangesAsync(cancellationToken)); } finally { context.Configuration.ValidateOnSaveEnabled = enabled; } }
public static async Task <bool> SaveAsync(System.Data.Entity.DbContext context, System.Threading.CancellationToken cancellationToken) { System.Data.Entity.Infrastructure.DbUpdateConcurrencyException exception; try { await context.SaveChangesAsync(cancellationToken); return(true); } catch (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException ex) { exception = ex; } catch (Exception) { throw; } await exception.Entries.Single().ReloadAsync(cancellationToken); return(false); }