我正在使用ASP.NET Core 2.1和EF Core 2.1开发一个项目.虽然大多数查询和命令都使用EF,但某些单元需要直接调用存储过程.
我不能使用FromSql,因为它需要基于实体模型的结果集.
我们假设我们有这些方法:
public Task CommandOne(DbContext context)
{
Entity entity = new Entity
{
Name = "Name"
};
context.DbSet<Entity>().Add(entity);
return context.SaveChangesAsync();
}
public async Task CommandTwo(DbContext context)
{
DbCommand command = context.Database.GetDbConnection().CreateCommand();
command.CommandText = "storedProcName";
command.CommandType = System.Data.CommandType.StoredProcedure;
using (var reader = await command.ExecuteReaderAsync().ConfigureAwait(false))
{
// read result sets
}
}
Run Code Online (Sandbox Code Playgroud)
如果我在一个事务中调用这两个命令,如下所示:
public async Task UnitOfWork(DbContext dbContext)
{
using (var transaction = await dbContext.Database.BeginTransactionAsync())
{
await CommandOne(dbContext);
await CommandTwo(dbContext);
}
}
Run Code Online (Sandbox Code Playgroud)
这个例外将会发生:
当分配给命令的连接处于挂起的本地事务中时,BeginExecuteReader要求该命令具有事务.该命令的Transaction属性尚未初始化.
我不得不提,它不是那么简单command.Transaction …