我遇到了例外-
InvalidOperationException。
System.Data.SqlClient.SqlTransaction.ZombieCheck()+1405089
System.Data.SqlClient.SqlTransaction.Commit()+76
我在Ado.Net上有一个Repository
模式。但是现在尝试在数据库中添加用户时遇到了这个问题。
我正在使用Ninject
之类的IoC
。
我可以在数据库中添加一个用户,但是当我尝试添加第二个用户并推送表单时。我在交易错误下方收到此消息。
public class AdoNetUnitOfWork : IUnitOfWork
{
private IUserRepository userRepository;
private ICompanyRepository companyRepository;
private IDbTransaction transaction;
private readonly IContext context;
public AdoNetUnitOfWork(IContext context)
{
this.context = context;
transaction = context.Transaction;
}
public ICallRepository CallRepository => throw new NotImplementedException();
public IUserRepository UserRepository => userRepository ?? new UserRepository(context);
public ICompanyRepository CompanyRepository => companyRepository ?? new CompanyRepository(context);
public void Dispose()
{
if(transaction != null)
{
transaction.Dispose();
transaction = null;
}
}
public bool SaveChanges()
{
if (transaction == null) throw new InvalidOperationException("Save change of transaction is not correct");
transaction.Commit();
transaction = null;
return true;
}
}
public class DbContext : IContext
{
private readonly IDbConnection connection;
public IDbTransaction Transaction { get; private set; }
public DbContext(IDbConnection connection)
{
this.connection = connection ?? throw new ArgumentException("connection is empty");
this.connection.Open();
Transaction = this.connection.BeginTransaction();
}
public IDbCommand CreateCommand()
{
var cmd = connection.CreateCommand();
cmd.Transaction = Transaction;
return cmd;
}
public class UserRepository : RepositoryBase<User>, IUserRepository
{
public UserRepository(IContext context) : base(context)
{ }
public IEnumerable<User> GetUsers()
{
using (var command = dbContext.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "spGetUsers";
return ToList(command);
}
}
public void AddUser(User user)
{
using (IDbCommand command = dbContext.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "spAddUser";
command.Parameters.Add(new SqlParameter("@FirstName", user.FirstName));
command.Parameters.Add(new SqlParameter("@LastName", user.LastName));
command.Parameters.Add(new SqlParameter("@Login", user.Login));
command.Parameters.Add(new SqlParameter("@Email", user.Email));
command.Parameters.Add(new SqlParameter("@Password", user.Password));
command.ExecuteNonQuery();
}
}
public class NinjectRegistration : NinjectModule
{
public override void Load()
{
Bind<IUnitOfWork>().To<AdoNetUnitOfWork>()
.WithConstructorArgument("context", new DbContext
(new SqlConnection(ConfigurationManager.ConnectionStrings["HolidayCRMDataBase"].ConnectionString)));
}
}