Эта SqlTransaction завершена; его повторное использование невозможно - PullRequest
0 голосов
/ 06 января 2019

Я получаю исключение-

InvalidOperationException.

System.Data.SqlClient.SqlTransaction.ZombieCheck () + 1405089

System.Data.SqlClient.SqlTransaction.Commit () + 76

У меня есть шаблон Repository в Ado.Net. Но теперь у меня возникает эта проблема при попытке добавить пользователя в базу данных.

Я использую 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)));


        }
    }
...