当我尝试在VS Code中以开发模式在ASP.NET Core环境中使用SaveChangesAsync和MySql EntityFramewok时,我遇到了错误。其他一切都很好。使用SaveChanges()时没有问题,没有异步。不知道是否有其他人有此问题。
错误如下所示:
InvalidOperationException:Connection必须有效并且打开以提交事务 MySql.Data.MySqlClient.MySqlTransaction.Commit()
控制器中的代码片段如下所示:
[HttpPut("/api/strategy/{id}")]
public async Task<IActionResult> UpdateStrategy(int id, [FromBody] StrategyResource newStrategy)
{
if(!ModelState.IsValid)
return BadRequest(ModelState);
mapper.Map<StrategyResource, Strategy>(newStrategy, strategyInDb );
context.SaveChanges(); // works fine
//await context.SaveChangesAsync(); gives ERROR
var res = mapper.Map<Strategy, StrategyResource>(strategyInDb );
return Ok(res);
}
控制器构造函数中的上下文初始化(真的没什么特别的)
private readonly JTradeContext context;
private readonly IMapper mapper;
public TradesController(JTradeContext context, IMapper mapper)
{
this.mapper = mapper;
this.context = context;
}
最初将Context添加到启动类
中的服务public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<JTradeContext>();
}
最后是上下文类本身
public class JTradeContext:DbContext
{
public DbSet<Trade> Trades { get; set; }
public DbSet<WebClient> WebClients { get; set; }
public DbSet<Strategy> Strategies { get; set; }
public DbSet<Portfolio> Portfolios { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("my connection string here");
}
}