public void AddNewCustomer() { using (IDbContext context = new NorthwindFakeContext()) using (IUnitOfWork unitOfWork = new UnitOfWork(context)) using (ICustomerService customerService = new CustomerService(unitOfWork)) { var newCustomer = new Customer { Address = "2100 Ross Ave", City = "Dallas", CompanyName = "CBRE", ContactTitle = "Software Engineer", Country = "US", CustomerID = "CBRE", Fax = "2222222222", Phone = "1111111111", PostalCode = "75042", Region = "Dallas" }; customerService.Add(newCustomer); unitOfWork.Save(); var savedCustomer = customerService.GetCustomer("CBRE"); Assert.AreEqual(newCustomer.CustomerID, savedCustomer.CustomerID); } }
public void UnitOfWork_Transaction_Test() { using(IDataContextAsync context = new NorthwindContext()) using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context)) { IRepositoryAsync<Customer> customerRepository = new Repository<Customer>(context, unitOfWork); IService<Customer> customerService = new CustomerService(customerRepository); try { unitOfWork.BeginTransaction(); customerService.Insert(new Customer { CustomerID = "YODA", CompanyName = "SkyRanch", ObjectState = ObjectState.Added}); customerService.Insert(new Customer { CustomerID = "JEDI", CompanyName = "SkyRanch", ObjectState = ObjectState.Added}); var customer = customerService.Find("YODA"); Assert.AreSame(customer.CustomerID, "YODA"); customer = customerService.Find("JEDI"); Assert.AreSame(customer.CustomerID, "JEDI"); // save var saveChangesAsync = unitOfWork.SaveChanges(); //Assert.AreSame(saveChangesAsync, 2); // Will cause an exception, cannot insert customer with the same CustomerId (primary key constraint) customerService.Insert(new Customer { CustomerID = "JEDI", CompanyName = "SkyRanch", ObjectState = ObjectState.Added }); //save unitOfWork.SaveChanges(); unitOfWork.Commit(); } catch (Exception e) { unitOfWork.Rollback(); } } }