public string Insert(LoaiSach cate) { { db.LoaiSaches.Add(cate); db.SaveChanges(); return(cate.MaLoaiSach); } }
public long Insert(User entity) // ham dung de them moi user vao ban ghi, { { db.Users.Add(entity); db.SaveChanges(); return(entity.IdUser); } }
public string Insert(TacGia author) { { db.TacGias.Add(author); db.SaveChanges(); return(author.MaTacGia); } }
public long Insert(SanPham sp) { { db.SanPhams.Add(sp); db.SaveChanges(); return(sp.MaSach); } }
internal static void AddRoleToUser(OnlineStoreDbContext dbContext, User user, IdentityRole role) { dbContext.Users.Add(user); dbContext.Roles.Add(role); dbContext.SaveChanges(); var dbUserRole = new IdentityUserRole <string>() { UserId = user.Id, RoleId = role.Id }; dbContext.UserRoles.Add(dbUserRole); dbContext.SaveChanges(); }
public int SaveChanges() { try { return(Db.SaveChanges()); } catch (DbUpdateConcurrencyException ex) { //A concurrency error occurred //Should handle intelligently Console.WriteLine(ex); throw; } catch (RetryLimitExceededException ex) { //DbResiliency retry limit exceeded //Should handle intelligently Console.WriteLine(ex); throw; } catch (Exception ex) { //Should handle intelligently Console.WriteLine(ex); throw; } }
private async Task <bool> CallCancelOrderAsync(OnlineStoreDbContext dbContext, Order order) { dbContext.Orders.Add(order); dbContext.SaveChanges(); var service = this.GetService(dbContext); var result = await service.CancelOrderAsync(order.Id); return(result); }
private async Task <bool> CallDeleteAsync(OnlineStoreDbContext dbContext, Product product) { dbContext.Products.Add(product); dbContext.SaveChanges(); var service = this.GetService(dbContext); var result = await service.DeleteAsync(product.Id); return(result); }
public static OnlineStoreDbContext SeedOrders(this OnlineStoreDbContext dbContext) { var orderHeader = new OrderHeader { OrderHeaderID = 1, OrderStatusID = 100, CustomerID = 1000, EmployeeID = 1, OrderDate = DateTime.Now, Total = 29.99m, CurrencyID = "USD", PaymentMethodID = Guid.Parse("44C3737C-9993-448A-82F7-75C0E37E5A7F"), Comments = "Order from unit tests", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.OrderHeaders.Add(orderHeader); dbContext.SaveChanges(); var orderDetail = new OrderDetail { OrderHeaderID = orderHeader.OrderHeaderID, ProductID = 1, ProductName = "The King of Fighters XIV", UnitPrice = 29.99m, Quantity = 1, Total = 29.99m, CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.OrderDetails.Add(orderDetail); dbContext.SaveChanges(); return(dbContext); }
public bool Insert(ChiTietDonHang detail) { try { db.ChiTietDonHangs.Add(detail); db.SaveChanges(); return(true); } catch (Exception e) { return(false); } }
public static void Initialize(OnlineStoreDbContext context) { if (!context.Products.Any()) { context.Products.AddRange( new Product { Name = "iPhone 6S", ImgSrc = "http://brain-images.cdn.dixons.com/5/8/10151585/u_10151585.jpg", Type = ProductType.Phone, Description = "A phone Apple's company.", Cost = 600 }, new Product { Name = "iPhone 8", ImgSrc = "https://www.poloinvest.ru/wp-content/uploads/2017/04/iphone8.jpg", Type = ProductType.Phone, Description = "A phone Apple's company.", Cost = 800 }, new Product { Name = "Xiaomi Mi Notebook Air", ImgSrc = "https://avatars.mds.yandex.net/get-mpic/397397/img_id3038328375620920498.jpeg/orig", Type = ProductType.Notebook, Description = "Very powerful notebook by Xiaomi.", Cost = 1000 }, new Product { Name = "Lenovo IdeaPad", ImgSrc = "https://s3-ap-southeast-2.amazonaws.com/wc-prod-pim/JPEG_1000x1000/SL14I100SS_lenovo_ideapad_100_14_celeron_laptop_100_14iby.jpg", Type = ProductType.Notebook, Description = "Good notebook for working and learning", Cost = 1550 }, new Product { Name = "Nikon D5", ImgSrc = "http://cdn-4.nikon-cdn.com/e/Q5NM96RZZo-YRYNeYvAi9beHK4x3L-8go_p7JUL6JpQMwSj_xzTyyQ==/Views/1557_D5_front.png", Type = ProductType.Camera, Description = "Professional camera.", Cost = 2050 } ); context.SaveChanges(); } }
public static void SeedAdmins() { var adminUser = new User { UserName = "******", Email = "*****@*****.**", PhoneNumber = "+36123456789", }; var adminPassword = "******"; var adminRole = new IdentityRole("Administrator"); var result1 = userManager.CreateAsync(adminUser, adminPassword).Result; var result2 = roleManager.CreateAsync(adminRole).Result; var result3 = userManager.AddToRoleAsync(adminUser, adminRole.Name).Result; dbContext.SaveChanges(); var path = Directory.GetCurrentDirectory(); var pathOfFile = Path.Combine(path, @"Initializer\testfile.png"); var file = new Dal.Entities.File { Content = System.IO.File.ReadAllBytes(pathOfFile), Thumbnail = System.IO.File.ReadAllBytes(pathOfFile), UserId = adminUser.Id, Price = 1000, UploadTime = DateTime.Now, Filename = "testfile.caff", Description = "test file" }; dbContext.Files.Add(file); dbContext.SaveChanges(); }
public static OnlineStoreDbContext SeedCountryCurrencies(this OnlineStoreDbContext dbContext) { var countryCurrency = new CountryCurrency { CountryID = 1, CurrencyID = "USD", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.CountryCurrencies.Add(countryCurrency); dbContext.SaveChanges(); return(dbContext); }
public static OnlineStoreDbContext SeedPaymentMethods(this OnlineStoreDbContext dbContext) { var paymentMethod = new PaymentMethod { PaymentMethodID = Guid.Parse("44C3737C-9993-448A-82F7-75C0E37E5A7F"), PaymentMethodDescription = "Credit Card", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.PaymentMethods.Add(paymentMethod); dbContext.SaveChanges(); return(dbContext); }
public static OnlineStoreDbContext SeedCountries(this OnlineStoreDbContext dbContext) { var country = new Country { ID = 1, CountryName = "USA", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Countries.Add(country); dbContext.SaveChanges(); return(dbContext); }
public static OnlineStoreDbContext SeedOrderStatuses(this OnlineStoreDbContext dbContext) { var orderStatus = new OrderStatus { OrderStatusID = 100, Description = "Created", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.OrderStatuses.Add(orderStatus); dbContext.SaveChanges(); return(dbContext); }
public static OnlineStoreDbContext SeedProductCategories(this OnlineStoreDbContext dbContext) { var productCategory = new ProductCategory { ProductCategoryID = 1, ProductCategoryName = "PS4 Games", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.ProductCategories.Add(productCategory); dbContext.SaveChanges(); return(dbContext); }
public static OnlineStoreDbContext SeedLocations(this OnlineStoreDbContext dbContext) { var location = new Location { LocationID = "W01", LocationName = "Warehouse 01", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Warehouses.Add(location); dbContext.SaveChanges(); return(dbContext); }
public static OnlineStoreDbContext SeedCurrencies(this OnlineStoreDbContext dbContext) { var currency = new Currency { CurrencyID = "USD", CurrencyName = "US Dollar", CurrencySymbol = "$", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Currencies.Add(currency); dbContext.SaveChanges(); return(dbContext); }
public static OnlineStoreDbContext SeedShippers(this OnlineStoreDbContext dbContext) { var shipper = new Shipper { ShipperID = 1, CompanyName = "DHL", ContactName = "Ricardo A. Bartra", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Shippers.Add(shipper); dbContext.SaveChanges(); return(dbContext); }
public static OnlineStoreDbContext SeedCustomers(this OnlineStoreDbContext dbContext) { var customer = new Customer { CustomerID = 1, CompanyName = "Best Buy", ContactName = "Colleen Dunn", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Customers.Add(customer); dbContext.SaveChanges(); return(dbContext); }
public static OnlineStoreDbContext SeedEmployees(this OnlineStoreDbContext dbContext) { var employee = new Employee { EmployeeID = 1, FirstName = "John", LastName = "Doe", BirthDate = DateTime.Now.AddYears(-25), CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Employees.Add(employee); dbContext.SaveChanges(); return(dbContext); }
public static OnlineStoreDbContext SeedProductInventories(this OnlineStoreDbContext dbContext) { var productInventory = new ProductInventory { ProductID = 1000, LocationID = "W01", OrderDetailID = 1, Quantity = 1500, CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.ProductInventories.Add(productInventory); dbContext.SaveChanges(); return(dbContext); }
public static OnlineStoreDbContext SeedProducts(this OnlineStoreDbContext dbContext) { var product = new Product { ProductID = 1, ProductName = "The King of Fighters XIV", ProductCategoryID = 1, UnitPrice = 29.99m, Description = "KOF XIV", Discontinued = false, Stocks = 15000, CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Products.Add(product); dbContext.SaveChanges(); return(dbContext); }
public UnitTests() { var services = new TestServiceBase(); var serviceProvider = services.BuildServiceProvider(); context = serviceProvider.GetService <OnlineStoreDbContext>(); var accessMock = new AccessMock(context); var mapper = MapperConfig.ConfigureAutoMapper(); var factory = serviceProvider.GetService <ILoggerFactory>(); var logger = factory.CreateLogger <UserService>(); var someOptions = Options.Create(new JwtOptions()); var validator = new MockValidator(); service = new UserService(null, null, null, someOptions, context, mapper, accessMock, logger, validator); var fileLogger = factory.CreateLogger <FileService>(); fileService = new FileService(accessMock, context, mapper, fileLogger, validator); var testUser = new User { UserName = "******", Email = "*****@*****.**", PhoneNumber = "+36123456789", }; if (context.ApplicationUsers.Count() < 1) { context.ApplicationUsers.Add(testUser); } context.SaveChanges(); }
static void Main(string[] args) { var context = new OnlineStoreDbContext(); //Customer var emp = new CustomerRepository(context); var customer1 = new Customer { CustomerID = Guid.NewGuid(), CustomerName = "Vandolph", CreditLimit = 1000, IsActive = true }; emp.Create(customer1); var customer2 = new Customer { CustomerID = Guid.NewGuid(), CustomerName = "Vandolph", CreditLimit = 1000, IsActive = true }; var emp2 = new CustomerRepository(context); emp.Delete(customer2); var customers = from c in context.Departments select c; var page2 = customers.Skip(40) .Take(40) .ToList(); context.Dispose(); //Add Department var tmg = new Department { DepartmentID = Guid.NewGuid(), DepartmentName = "Technology Management", IsActive = true }; var bdg = new Department { DepartmentID = Guid.NewGuid(), DepartmentName = "Business Development", IsActive = true }; context.Departments.Add(tmg); context.Departments.Add(bdg); context.SaveChanges(); #region Add Employee var simon = new Employee { EmployeeID = Guid.NewGuid(), FirstName = "Simon", MiddleName = "D.", LastName = "Bradecina", Department = tmg }; var bjae = new Employee { EmployeeID = Guid.NewGuid(), FirstName = "Bjae", MiddleName = "A.", LastName = "Bradecina", Department = tmg }; //product var prod = new Product { ProductID = Guid.NewGuid(), ProductName = "Candy", IsActive = true }; context.Product.Add(prod); context.SaveChanges(); #endregion #region Create Record context.Employees.Add(simon); context.Employees.Add(bjae); context.SaveChanges(); #endregion #region Delete Record var s = new Employee { EmployeeID = Guid.NewGuid(), FirstName = "Vicente", MiddleName = "B.", LastName = "Bradecina", Department = tmg }; context.Employees.Add(s); context.SaveChanges(); var b = new Employee { EmployeeID = Guid.NewGuid(), FirstName = "Roselyn", MiddleName = "D.", LastName = "Bradecina", Department = tmg }; s = context.Employees.Find(s.EmployeeID); context.Employees.Remove(s); context.SaveChanges(); #endregion #region Update Record var n = new Employee { EmployeeID = Guid.NewGuid(), FirstName = "Annabeth", MiddleName = "G..", LastName = "Susvilla", Department = tmg }; var e = new Employee { EmployeeID = Guid.NewGuid(), FirstName = "Ezekiel", MiddleName = "D.", LastName = "Bradecina", Department = tmg }; context.Employees.Add(e); context.SaveChanges(); s = context.Employees.Find(e.EmployeeID); context.Employees.Update(e); context.SaveChanges(); #endregion #region Retrieve Records var departments = from d in context.Departments select d; var page3 = departments.Skip(40) .Take(40) .ToList(); var tmgEmployees = from empl in context.Employees join d in context.Departments on empl.DepartmentID equals d.DepartmentID where d.DepartmentName.Equals("Technollogy Management") orderby e.LastName select new { FullName = empl.FirstName + "" + empl.MiddleName.Substring(0, 1), empl.LastName, Department = d.DepartmentName }; var result = tmgEmployees.ToList(); context.Dispose(); }
public async System.Threading.Tasks.Task <IActionResult> OnPostSaveOrderAsync([FromBody] OrderAddressViewModel model) { if (!ModelState.IsValid) { IEnumerable <ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors); return(new BadRequestObjectResult("Đặt hàng không thành công")); } using (var context = new OnlineStoreDbContext()) { using (var transaction = context.Database.BeginTransaction()) { try { var user = _userManager.GetUserAsync(HttpContext.User).Result; if (user == null) { return(new BadRequestObjectResult("Tất cả sản phẩm trong giỏ không thể đặt. Vui lòng kiểm tra lại giỏ hàng.")); } var cart = _cartRepository.GetCartByCustomerId(user.Id); if (cart == null) { return(new BadRequestObjectResult("Tất cả sản phẩm trong giỏ không thể đặt. Vui lòng kiểm tra lại giỏ hàng.")); } var newAddress = new Address(); if (model.Order.ReceivingTypeId == 3) { newAddress = new Address { CustomerId = user.Id, PhoneNumber = model.Address.PhoneNumber, RecipientName = model.Address.RecipientName, ShowRoomAddressId = model.Address.ShowRoomAddressId, DateCreated = DateTime.Now, DateModified = DateTime.Now }; context.Address.Add(newAddress); context.SaveChanges(); } var receivingType = _receivingTypeRepository.Find(model.Order.ReceivingTypeId); var newOrder = new DAL.Data.Entities.Order { DateCreated = DateTime.Now, DateModified = DateTime.Now, DeliveryDate = DateTime.Now.AddDays(receivingType.NumberShipDay), ShippingFee = model.Order.ShippingFee, SubTotal = cart.CartDetails.Sum(x => x.Item.Price * x.Quantity), OrderDate = DateTime.Now, PaymentType = model.Order.PaymentType, ReceivingTypeId = model.Order.ReceivingTypeId, SaleOff = model.Order.SaleOff, Status = model.Order.Status == OrderStatus.ReadyToDeliver ? OrderStatus.ReadyToDeliver : OrderStatus.Pending, }; if (model.Order.PaymentType == PaymentType.CreditDebitCard) { Address addressForOnlinePayment = new Address { CustomerId = user.Id, Detail = "", DateCreated = DateTime.Now, RecipientName = user.Name ?? "", PhoneNumber = user.PhoneNumber ?? "" }; context.Address.Add(addressForOnlinePayment); context.SaveChanges(); newOrder.AddressId = addressForOnlinePayment.Id; } else { newOrder.AddressId = model.Order.ReceivingTypeId == 3 ? newAddress.Id : model.Order.AddressId; } newOrder.Total = newOrder.SubTotal + newOrder.ShippingFee - newOrder.SaleOff; context.Order.Add(newOrder); context.SaveChanges(); var items = cart.CartDetails.Where(cd => cd.IsDeleted == false && cd.Item.Quantity > 0).ToList(); if (items == null || items.Count() == 0) { transaction.Rollback(); return(new BadRequestObjectResult("Tất cả sản phẩm trong giỏ không thể đặt. Vui lòng kiểm tra lại giỏ hàng.")); } var itemsCheckout = TempData.Get <List <ItemCartViewModel> >(CommonConstants.ItemsCheckout); //if (itemsCheckout.Sum(x => x.Quantity) != items.Sum(x => x.Item.Quantity)) //{ // transaction.Rollback(); // return new BadRequestObjectResult("Các sản phẩm trong giỏ đã có sự thay đổi về số lượng từ hệ thống. Vui lòng kiểm tra lại giỏ hàng."); //} if (itemsCheckout.Sum(x => x.Price) != items.Sum(x => x.Item.Price)) { transaction.Rollback(); return(new BadRequestObjectResult("Các sản phẩm trong giỏ đã có sự thay đổi về giá từ hệ thống. Vui lòng kiểm tra lại giỏ hàng.")); } foreach (var itemInCart in items) { if (itemsCheckout.Any(x => x.Quantity > itemInCart.Item.Quantity)) { transaction.Rollback(); return(new BadRequestObjectResult("Các sản phẩm trong giỏ đã có sự thay đổi về số lượng từ hệ thống. Vui lòng kiểm tra lại giỏ hàng.")); } var item = _itemRepository.Find(itemInCart.ItemId); if (item.IsDeleted == false) { if (itemInCart.Quantity > item.Quantity) { transaction.Rollback(); return(new BadRequestObjectResult("Sản phẩm không còn đủ số lượng cho đơn hàng. Quá trình đặt hàng thất bại. Vui lòng kiểm tra lại giỏ hàng")); } var newOrderItem = new OrderItem { OrderId = newOrder.Id, Price = item.Price, ItemId = itemInCart.ItemId, Quantity = itemInCart.Quantity, DateCreated = DateTime.Now, DateModified = DateTime.Now, SaleOff = 0, IsDeleted = false, Amount = item.Price * itemInCart.Quantity }; context.OrderItem.Add(newOrderItem); context.SaveChanges(); item.Quantity -= itemInCart.Quantity; context.Item.Update(item); context.SaveChanges(); } } cart.IsDeleted = true; context.Cart.Update(cart); context.SaveChanges(); var cartDetails = cart.CartDetails; foreach (var cartDetail in cartDetails) { cartDetail.IsDeleted = true; cartDetail.Quantity = 0; context.CartDetail.Update(cartDetail); context.SaveChanges(); } transaction.Commit(); var url = Url.Page("/Order/MyOrder", pageHandler: null, values: new { orderId = newOrder.Id }, protocol: Request.Scheme); var confirmAccountModel = new OrderEmailViewModel { Url = url, LetterDescription = $@"Yêu cầu đặt hàng cho đơn hàng #{newOrder.Id} của bạn đã được tiếp nhận và đang chờ nhà bán hàng xử lý. Thời gian đặt hàng vào lúc {string.Format("{0:HH:mm}", newOrder.OrderDate)} ngày {string.Format("{0:d/M/yyyy}", newOrder.OrderDate)}. Chúng tôi sẽ tiếp tục cập nhật với bạn về trạng thái tiếp theo của đơn hàng." }; string body = await _razorViewToStringRenderer.RenderViewToStringAsync("~/Pages/Emails/ConfirmOrderEmail.cshtml", confirmAccountModel); await _emailSender.SendEmailAsync(user.Email, "Xác nhận đơn hàng từ TimiShop", body); return(new OkObjectResult(new { orderId = newOrder.Id, email = user.Email })); } catch (Exception ex) { transaction.Rollback(); return(new BadRequestObjectResult("Đặt hàng không thành công")); } } } }
public long Insert(GopY_KH contact) { db.GopY_KH.Add(contact); db.SaveChanges(); return(contact.IdGopY); }
public static void SeedInMemory(this OnlineStoreDbContext dbContext) { var creationUser = "******"; var creationDateTime = DateTime.Now; var country = new Country { CountryID = 1, CountryName = "USA", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Countries.Add(country); var currency = new Currency { CurrencyID = "USD", CurrencyName = "US Dollar", CurrencySymbol = "$", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Currencies.Add(currency); var countryCurrency = new CountryCurrency { CountryID = country.CountryID, CurrencyID = currency.CurrencyID, CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.CountryCurrencies.Add(countryCurrency); dbContext.SaveChanges(); var employee = new Employee { EmployeeID = 1, FirstName = "John", LastName = "Doe", BirthDate = DateTime.Now.AddYears(-25), CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Employees.Add(employee); dbContext.SaveChanges(); var productCategory = new ProductCategory { ProductCategoryID = 1, ProductCategoryName = "PS4 Games", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.ProductCategories.Add(productCategory); var product = new Product { ProductID = 1, ProductName = "The King of Fighters XIV", ProductCategoryID = 1, UnitPrice = 29.99m, Description = "KOF XIV", Discontinued = false, Stocks = 15000, CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Products.Add(product); var location = new Location { LocationID = "W0001", LocationName = "Warehouse 001", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Warehouses.Add(location); var productInventory = new ProductInventory { ProductID = product.ProductID, LocationID = location.LocationID, OrderDetailID = 1, Quantity = 1500, CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.ProductInventories.Add(productInventory); dbContext.SaveChanges(); var orderStatus = new OrderStatus { OrderStatusID = 100, Description = "Created", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.OrderStatuses.Add(orderStatus); var paymentMethod = new PaymentMethod { PaymentMethodID = Guid.NewGuid(), PaymentMethodDescription = "Credit Card", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.PaymentMethods.Add(paymentMethod); var customer = new Customer { CustomerID = 1, CompanyName = "Best Buy", ContactName = "Colleen Dunn", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Customers.Add(customer); var shipper = new Shipper { ShipperID = 1, CompanyName = "DHL", ContactName = "Ricardo A. Bartra", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Shippers.Add(shipper); var order = new OrderHeader { OrderStatusID = orderStatus.OrderStatusID, CustomerID = customer.CustomerID, EmployeeID = employee.EmployeeID, OrderDate = DateTime.Now, Total = 29.99m, CurrencyID = "USD", PaymentMethodID = paymentMethod.PaymentMethodID, Comments = "Order from unit tests", CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.Orders.Add(order); var orderDetail = new OrderDetail { OrderHeaderID = order.OrderHeaderID, ProductID = product.ProductID, ProductName = product.ProductName, UnitPrice = 29.99m, Quantity = 1, Total = 29.99m, CreationUser = creationUser, CreationDateTime = creationDateTime }; dbContext.OrderDetails.Add(orderDetail); dbContext.SaveChanges(); }
public long Insert(DonHang order) { db.DonHangs.Add(order); db.SaveChanges(); return(order.MaDonHang); }