public static void Seed(this BookstoreDbContext context) { if (!context.Role.Any()) { context.Add(new Role { Name = "Admin" }); context.Add(new Role { Name = "User" }); context.SaveChanges(); } if (!context.User.Any()) { var adminUser = new User { Email = "*****@*****.**", FirstName = "Admin", LastName = "Admin", Username = "******", Password = "******" }; context.Add(adminUser); context.SaveChanges(); if (!context.UserRoleMapping.Any()) { context.UserRoleMapping.Add(new UserRoleMapping { UserId = adminUser.Id, RoleId = context.Role.FirstOrDefault(x => x.Name == "Admin")?.Id ?? throw new InvalidOperationException() });
//Khi thanh toán Ngan Luong XOng public ActionResult confirm_orderPaymentOnline() { String Token = Request["token"]; RequestCheckOrder info = new RequestCheckOrder(); info.Merchant_id = nganluongInfo.Merchant_id; info.Merchant_password = nganluongInfo.Merchant_password; info.Token = Token; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseCheckOrder result = objNLChecout.GetTransactionDetail(info); if (result.errorCode == "00") { String codeOrder = Session["OrderId"].ToString(); var OrderInfo = db.Orders.OrderByDescending(m => m.code == codeOrder).FirstOrDefault(); OrderInfo.StatusPayment = 1; db.Entry(OrderInfo).State = EntityState.Modified; db.SaveChanges(); ViewBag.paymentStatus = OrderInfo.StatusPayment; ViewBag.Methodpayment = OrderInfo.deliveryPaymentMethod; return(View("oderComplete", OrderInfo)); } else { ViewBag.status = false; } return(View("confirm_orderPaymentOnline")); }
public bool insert(Order entity, DetailOrder[] items) { try { entity.CreatedAt = DateTime.Now; entity.Status = false; db.Orders.Add(entity); db.SaveChanges(); ProductService serv = new ProductService(); Product temp = null; foreach (DetailOrder item in items) { item.OrderId = entity.id; temp = serv.findById(item.ProductId); temp.Quantity = temp.Quantity.Value - item.Quantity.Value; serv.update(temp); } db.DetailOrders.AddRange(items); db.SaveChanges(); return(true); } catch { return(false); } }
//status public ActionResult Status(int id) { Morder morder = db.Orders.Find(id); db.Entry(morder).State = EntityState.Modified; db.SaveChanges(); Message.set_flash("Thay đổi trang thái thành công", "success"); return(RedirectToAction("Index")); }
public ActionResult Purchase(Purchase purchase) { if (ModelState.IsValid) { db.Purchases.Add(purchase); db.SaveChanges(); return(View("Purchases", db.Purchases)); } return(View()); }
//status public ActionResult Status(int id) { Morder morder = db.Orders.Find(id); morder.status = (morder.status == 1) ? 2 : 1; morder.updated_at = DateTime.Now; morder.updated_by = int.Parse(Session["Admin_id"].ToString()); db.Entry(morder).State = EntityState.Modified; db.SaveChanges(); Message.set_flash("Thay đổi trang thái thành công", "success"); return(RedirectToAction("Index")); }
public long insert(Category entity) { try { db.Categories.Add(entity); db.SaveChanges(); return(entity.id); } catch { return(-1); } }
public virtual IQueryable <T> Items => set; // Можем переопределить в наследниках нюансы чтения\добавления сущностей // Добавление в бд public T Add(T item) { if (item is null) { throw new ArgumentNullException(nameof(item)); } db.Entry(item).State = EntityState.Added; // если элемент не пустой, то отмечаем сущность как добавленную if (AutoSaveChanges) { db.SaveChanges(); } return(item); }
public long insert(Product entity) { try { entity.CreatedAt = DateTime.Now; db.Products.Add(entity); db.SaveChanges(); return(entity.id); } catch { return(-1); } }
public bool Insert(TEntity entity) { try { _context.Add(entity); _context.SaveChanges(); return(true); } catch (Exception e) { return(false); } }
public long insert(Account entity) { try { entity.CreatedAt = DateTime.Now; entity.Status = true; db.Accounts.Add(entity); db.SaveChanges(); return(entity.id); } catch { return(-1); } }
public ActionResult Create(Book newBook) { //TODO: Add the new book to the database db.Books.Add(newBook); db.SaveChanges(); return(View()); }
public ActionResult Create(Book newBook) { //TODO: Add the new book to the database db.Books.Add(newBook); //taken from model dbContext db.SaveChanges(); return(View()); }
public ActionResult Create(Product mbook, HttpPostedFileBase file) { ViewBag.listCate = db.Categorys.Where(m => m.status != 0 && m.ID > 2).ToList(); if (ModelState.IsValid) { string slug = Mystring.ToSlug(mbook.name.ToString()); if (db.Categorys.Where(m => m.slug == slug).Count() > 0) { Message.set_flash("Sản phẩm đã tồn tại trong bảng Category", "danger"); return(View(mbook)); } if (db.Products.Where(m => m.slug == slug).Count() > 0) { Message.set_flash(" Sản phẩm đã tồn tại trong bảng book", "danger"); return(View(mbook)); } // lấy tên loại sản phẩm var namecateDb = db.Categorys.Where(m => m.ID == mbook.catid).First(); string namecate = Mystring.ToStringNospace(namecateDb.name); // lấy tên ảnh file = Request.Files["img"]; string filename = file.FileName.ToString(); //lấy đuôi ảnh string ExtensionFile = Mystring.GetFileExtension(filename); // lấy tên sản phẩm làm slug //lấy tên mới của ảnh slug + [đuôi ảnh lấy đc] string namefilenew = namecate + "/" + slug + "." + ExtensionFile; //lưu ảnh vào đường đẫn var path = Path.Combine(Server.MapPath("~/public/images/product"), namefilenew); //nếu thư mục k tồn tại thì tạo thư mục var folder = Server.MapPath("~/public/images/product/" + namecate); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } file.SaveAs(path); mbook.img = namefilenew; mbook.slug = slug; mbook.created_at = DateTime.Now; mbook.created_by = int.Parse(Session["Admin_id"].ToString()); db.Products.Add(mbook); db.SaveChanges(); //create Link link tt_link = new link(); tt_link.slug = slug; tt_link.tableId = 1; tt_link.type = "ProductDetail"; tt_link.parentId = mbook.ID; db.Link.Add(tt_link); db.SaveChanges(); Message.set_flash("Thêm thành công", "success"); return(RedirectToAction("index")); } Message.set_flash("Thêm Thất Bại", "danger"); return(View(mbook)); }
public ActionResult Create(Book newBook) { //TODO: Add the new book to the database if (ModelState.IsValid) { db.Books.Add(newBook); db.SaveChanges(); } return(View()); }
public ActionResult Create(Mslider mslider, HttpPostedFileBase file) { if (ModelState.IsValid) { file = Request.Files["img"]; string filename = file.FileName.ToString(); string slug = Mystring.ToSlug(mslider.name.ToString()); string ExtensionFile = Mystring.GetFileExtension(filename); string namefilenew = slug + "." + ExtensionFile; var path = Path.Combine(Server.MapPath("~/public/images/bg-images"), namefilenew); file.SaveAs(path); mslider.url = slug; mslider.img = namefilenew; mslider.created_at = DateTime.Now; mslider.updated_at = DateTime.Now; mslider.created_by = int.Parse(Session["Admin_id"].ToString()); mslider.updated_by = int.Parse(Session["Admin_id"].ToString()); db.Sliders.Add(mslider); db.SaveChanges(); Message.set_flash("Thêm thành công", "success"); return(RedirectToAction("Index")); } Message.set_flash("Thêm thất bại", "danger"); return(View(mslider)); }
public ActionResult Create(Muser muser, FormCollection data) { if (ModelState.IsValid) { string password1 = data["password1"]; string password2 = data["password2"]; string username = muser.username; var Luser = db.Users.Where(m => m.status == 1 && m.username == username); if (password1 != password2) { ViewBag.error = "PassWord không khớp"; } if (Luser.Count() > 0) { ViewBag.error1 = "Tên Đăng nhâp đã tồn tại"; } else { string pass = Mystring.ToMD5(password1); muser.img = "ádasd"; muser.password = pass; muser.address = ""; muser.created_at = DateTime.Now; muser.updated_at = DateTime.Now; muser.created_by = int.Parse(Session["Admin_id"].ToString()); muser.updated_by = int.Parse(Session["Admin_id"].ToString()); db.Users.Add(muser); db.SaveChanges(); Message.set_flash("Tạo user thành công", "success"); return(RedirectToAction("Index")); } } return(View(muser)); }
public ActionResult formCheckOut(FormCollection f) { //Muser user = (Muser)Session[Common.CommonConstants.CUSTOMER_SESSION]; var tenKH = f["deliveryname"]; var SDT = f["deliveryphone"]; var email = f["deliveryemail"]; var diaChi = f["deliveryaddress"]; var TongTien = f["sumOrder"]; Morder order = new Morder(); order.deliveryname = tenKH; order.deliveryphone = SDT; order.deliveryemail = email; order.deliveryaddress = diaChi; order.updated_at = DateTime.Today; db.Orders.Add(order); db.SaveChanges(); var cart = Session[SessionCart]; var list1 = new List <Cart_item>(); if (cart != null) { list1 = (List <Cart_item>)cart; } var orderid = db.Orders.OrderByDescending(m => m.ID).ToList()[0].ID; foreach (var item in list1) { Mordersdetail detail = new Mordersdetail(); detail.orderid = orderid; detail.productid = item.product.ID; detail.price = item.product.price; detail.quantity = item.quantity; detail.priceSale = item.product.pricesale; detail.amount = (detail.price * (100 - detail.priceSale) / 100) * detail.quantity; db.Ordersdetails.Add(detail); db.SaveChanges(); } return(View("OrderComplete")); }
static void Main() { Database.SetInitializer(new MigrateDatabaseToLatestVersion<BookstoreDbContext, Configuration>()); var db = new BookstoreDbContext(); db.Authors.Count(); var xmlController = new XmlController<CatalogXml>(); var books = xmlController.Deserialize(XmlInputPath).Books; foreach (var book in books) { var authors = new List<Author>(); if (book.Authors != null) { foreach (var auth in book.Authors) { authors.Add(new Author() { Name = auth }); } } var reviews = new List<Review>(); if (book.Reviews != null) { foreach (var review in book.Reviews) { reviews.Add(new Review() { Author = new Author() { Name = review.Author == null ? null : review.Author }, CreationDate = review.Date != null ? DateTime.Parse(review.Date) : DateTime.MinValue }); } } var bookToAdd = db.Books.Add(new Book() { Title = book.Title, Isbn = book.Isbn, Price = book.Price, WebSite = book.Website }); bookToAdd.Reviews = reviews; bookToAdd.Authors = authors; db.Books.Add(bookToAdd); } db.SaveChanges(); }
static void Main(string[] args) { var optionsBuilder = new DbContextOptionsBuilder <BookstoreDbContext>(); optionsBuilder.UseSqlServer(ConnectionString); var context = new BookstoreDbContext(optionsBuilder.Options); context.Database.Migrate(); var saeedGanji = Author.Create("Saeed", "Ganji", new DateTime(1985, 1, 1)); context.Authors.Add(saeedGanji); context.SaveChanges(); // // context.Database.Migrate(); // context.Database.EnsureCreated(); // // var me = Author.Create("Saeed", "Ganji", DateTime.Now.AddDays(-1)); // me.AddBook("EF Core" , "132465"); // // var other = Author.Create("John", "Doe", DateTime.Now.AddDays(-1)); // other.AddBook("No Idea", "132465"); // // context.Authors.AddRange(me,other); // // context.SaveChanges(); Author me = null; // mention AsNoTracking in the article me = context.Authors.AsNoTracking().FirstOrDefault(x => x.FirstName == "Saeed"); me.AddBook("SampleBook", "1234567-890"); context.SaveChanges(); Console.WriteLine(context.Entry(me).Property("CreatedOn").CurrentValue); }
//public static ShoppingCart GetCart(ISession session, BookstoreDbContext context) //{ // string cartId = session.GetString("CartId") ?? Guid.NewGuid().ToString(); // session.SetString("CartId", cartId); // return new ShoppingCart(context) { ShoppingCartId = cartId }; //} public void AddToCart(Book book, int amount) { var shoppingCartItem = _bookstoreDbContext.ShoppingCartItems.SingleOrDefault( s => s.Book.Id == book.Id && s.ShoppingCartId == ShoppingCartId); if (shoppingCartItem == null) { shoppingCartItem = new ShoppingCartItem { ShoppingCartId = ShoppingCartId, Book = book, Amount = 1 }; _bookstoreDbContext.ShoppingCartItems.Add(shoppingCartItem); } else { shoppingCartItem.Amount++; } _bookstoreDbContext.SaveChanges(); }
public ActionResult register(Muser muser, FormCollection fc) { string uname = fc["uname"]; string fname = fc["fname"]; string Pass = Mystring.ToMD5(fc["psw"]); string Pass2 = Mystring.ToMD5(fc["repsw"]); if (Pass2 != Pass) { ViewBag.error = "Mật khẩu không khớp"; return(View("loginEndRegister")); } string email = fc["email"]; string address = fc["address"]; string phone = fc["phone"]; if (ModelState.IsValid) { var Luser = db.Users.Where(m => m.status == 1 && m.username == uname && m.access == 1); if (Luser.Count() > 0) { ViewBag.error = "Tên Đăng Nhập đã tồn tại"; return(View("loginEndRegister")); } else { muser.img = "defalt.png"; muser.password = Pass; muser.username = uname; muser.fullname = fname; muser.email = email; muser.address = address; muser.phone = phone; muser.gender = "nam"; muser.access = 1; muser.created_at = DateTime.Now; muser.updated_at = DateTime.Now; muser.created_by = 1; muser.updated_by = 1; muser.status = 1; db.Users.Add(muser); db.SaveChanges(); Message.set_flash("Đăng ký tài khoản thành công ", "success"); return(View("loginEndRegister")); } } Message.set_flash("Đăng ký tài khoản thất bai", "danger"); return(View("loginEndRegister")); }
public ActionResult Edit(Muser muser) { if (ModelState.IsValid) { muser.img = "ádasd"; muser.access = 0; muser.created_at = DateTime.Now; muser.updated_at = DateTime.Now; muser.created_by = int.Parse(Session["Admin_id"].ToString()); muser.updated_by = int.Parse(Session["Admin_id"].ToString()); db.Entry(muser).State = EntityState.Modified; db.SaveChanges(); Message.set_flash("Cập nhật thành công", "success"); ViewBag.role = db.Roles.Where(m => m.parentId == muser.access).First(); return(View("_information", muser)); } Message.set_flash("Cập nhật Thất Bại", "danger"); ViewBag.role = db.Roles.Where(m => m.parentId == muser.access).First(); return(View("Edit", muser)); }
public JsonResult Edit(Muser muser) { string new_pass = Mystring.ToMD5(muser.password); var pass_account = db.Users.Where(m => m.password == new_pass).ToList().Count(); var uname_account = db.Users.Where(m => m.username == muser.username && m.ID != muser.ID).ToList().Count(); if (pass_account == 0) { Message.set_flash("Mật khẩu không đúng", "danger"); return(Json(new { statuss = 1 }, JsonRequestBehavior.AllowGet)); } else if (uname_account > 0) { Message.set_flash("Tên đăng nhập đã tồn tại", "danger"); return(Json(new { statuss = 2 }, JsonRequestBehavior.AllowGet)); } else { if (ModelState.IsValid) { Muser muser1 = db.Users.Find(muser.ID); muser.access = muser1.access; muser.img = muser1.img; muser.status = muser1.status; muser.password = new_pass; muser.created_at = muser1.created_at; muser.updated_at = DateTime.Now; muser.created_by = muser1.created_by; muser.updated_by = muser1.ID; db.Entry(muser1).CurrentValues.SetValues(muser); db.SaveChanges(); Session[Common.CommonConstants.CUSTOMER_SESSION] = null; Session.Add(CommonConstants.CUSTOMER_SESSION, muser); Message.set_flash("Cập nhật thành công", "success"); return(Json(muser, JsonRequestBehavior.AllowGet)); } } return(Json(new { statuss = 3 }, JsonRequestBehavior.AllowGet)); }
public ActionResult Create(Mcategory mcategory) { if (ModelState.IsValid) { //category string slug = Mystring.ToSlug(mcategory.name.ToString()); if (db.Categorys.Where(m => m.slug == slug).Count() > 0) { Message.set_flash("Loại sản phẩm đã tồn tại trong bảng Category", "danger"); return(View(mcategory)); } //topic if (db.Products.Where(m => m.slug == slug).Count() > 0) { Message.set_flash("Loại sản phẩm đã tồn tại trong bảng Product", "danger"); return(View(mcategory)); } mcategory.slug = slug; mcategory.created_at = DateTime.Now; mcategory.updated_at = DateTime.Now; mcategory.created_by = int.Parse(Session["Admin_id"].ToString()); mcategory.updated_by = int.Parse(Session["Admin_id"].ToString()); db.Categorys.Add(mcategory); db.SaveChanges(); //create Link link tt_link = new link(); tt_link.slug = slug; tt_link.tableId = 2; tt_link.type = "category"; tt_link.parentId = mcategory.ID; db.Link.Add(tt_link); db.SaveChanges(); Message.set_flash("Thêm thành công", "success"); return(RedirectToAction("index")); } Message.set_flash("Thêm Thất Bại", "danger"); ViewBag.listCate = db.Categorys.Where(m => m.status != 0).ToList(); return(View(mcategory)); }
private static void AddTestData(BookstoreDbContext context) { context.Database.ExecuteSqlCommand("Delete From Books"); var book1 = new Book(); book1.Title = "Anna Karenina"; book1.Author = "Leo Tolstoy"; context.Books.Add(book1); var book2 = new Book(); book2.Title = "Into the Wildnerness"; book2.Author = "Sarah Donati"; context.Books.Add(book2); var book3 = new Book(); book3.Title = "Harry Potter, Chamber of Secrets"; book3.Author = "JK Rowling"; context.Books.Add(book3); context.SaveChanges(); }
public void add(Book book) { db.Books.Add(book); db.SaveChanges(); }
private void save() { db.SaveChanges(); }
public void Add(Author entity) { db.Authors.Add(entity); db.SaveChanges(); }
public bool SaveChanges() { return(context.SaveChanges() > 0); }
public void add(Author author) { db.Authors.Add(author); db.SaveChanges(); }