public bool ThemDanhMuc(DANHMUC danhmuc) { try { MyDBContext context = new MyDBContext(); context.DANHMUCs.Add(danhmuc); context.SaveChanges(); return(true); } catch { return(false); } }
public bool ThemDiaChi(DIACHI dc) { try { MyDBContext context = new MyDBContext(); context.DIACHIs.Add(dc); context.SaveChanges(); return(true); } catch { return(false); } }
public bool ThemCTDonHang(CHITIETDONHANG dh) { try { MyDBContext context = new MyDBContext(); context.CHITIETDONHANGs.Add(dh); context.SaveChanges(); return(true); } catch { return(false); } }
public ActionResult Create([Bind(Include = "Id, Name, BaseAsset, QuoteAsset, LastPrice, Volumn24h, MarketId, CreatedAt, UpdatedAt, Status")] Coin coin) { if (ModelState.IsValid) { db.Coins.Add(coin); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.MarketId = new SelectList(db.Markets, "Id", "Name", coin.MarketId); return(View(coin)); }
public bool ThemQuanTri(TAIKHOANQUANTRI dc) { try { MyDBContext context = new MyDBContext(); context.TAIKHOANQUANTRIs.Add(dc); context.SaveChanges(); return(true); } catch { return(false); } }
public void Main(string[] args) { var config = new ConfigurationBuilder(@"C:\VSProjects\Precisionsoft\Decidify\trunk\Decidify.UI") .AddJsonFile("config.json"); var mongoProvider = new MongoDbAuditStoreProvider() .WithConfiguration(config.Build()) .Start(); using (var myDbContext = new MyDBContext(mongoProvider)) { myDbContext.Database.EnsureDeleted(); myDbContext.Database.EnsureCreated(); var customer = new Customer() { FirstName = "TestFirstName", LastName = "TEstLAstNAme" }; myDbContext.Customers.Add(customer); var auditablePropCount = customer.GetType() .GetProperties() .Count(p => !p.GetCustomAttributes(typeof(DoNotAudit), true).Any()); var nonAuditablePropCount = customer.GetType() .GetProperties() .Count(p => p.GetCustomAttributes(typeof(DoNotAudit), true).Any()); myDbContext.SaveChanges("Test User"); Console.WriteLine($"Added object with {auditablePropCount} auditable properties and {nonAuditablePropCount} non-auditable properties."); var auditLogs = myDbContext.GetAuditLogs()?.ToList(); Console.WriteLine($"Audit log contains {auditLogs?.Count()} entries."); //foreach (var auditLog in myDbContext.GetAuditLogs()) //{ // Console.WriteLine($"AuditLogId:{auditLog.AuditLogId} TableName:{auditLog.TableName} ColumnName:{auditLog.ColumnName} OriginalValue:{auditLog.OriginalValue} NewValue:{auditLog.NewValue} EventDateTime:{auditLog.EventDateTime}"); //} //if (auditLogs.Count() == auditablePropCount) // Console.WriteLine("Test succeeded."); //else // throw new Exception("Something is wrong."); Console.Read(); myDbContext.Database.EnsureDeleted(); } }
private void SaveBtn_OnClick(object sender, RoutedEventArgs e) { if (JobsGrid.SelectedItems.Count != 1) { return; } if (FrequencyComboBox.SelectedItem == null) { MessageBox.Show("You must select a frequency."); return; } using (var context = new MyDBContext()) { var job = (DataUpdateJobDetails)JobsGrid.SelectedItem; if (job.UseTag) { if (TagsComboBox.SelectedItem == null) { MessageBox.Show("You must select a tag."); return; } job.Instrument = null; job.InstrumentID = null; job.Tag = (Tag)TagsComboBox.SelectedItem; job.TagID = job.Tag.ID; } else //job is for a specific instrument, not a tag { if (InstrumentsComboBox.SelectedItem == null) { MessageBox.Show("You must select an instrument."); return; } job.Instrument = (Instrument)InstrumentsComboBox.SelectedItem; job.InstrumentID = job.Instrument.ID; job.Tag = null; job.TagID = null; } context.DataUpdateJobs.Attach(job); context.Entry(job).State = EntityState.Modified; context.SaveChanges(); } }
public void TestAdd() { using (var context = new MyDBContext()) { var client = OrderClientHelper.CreateOrderClient(); context.OrderClients.Add(client); int result = context.SaveChanges(); Assert.IsTrue(result == 1); Console.WriteLine(client); OrderClient clientFromDB = context.OrderClients .FirstOrDefault(c => c.ClientID == client.ClientID); Assert.IsNotNull(clientFromDB); Assert.IsTrue(client.Equals(clientFromDB)); } }
private void deleteClientButton_Click(object sender, RoutedEventArgs e) { try { if (clientGrid.SelectedItem != null) { var deleted = (Client)clientGrid.SelectedItem; var list = (from item in DBContext.Clients.ToList() where item.ID.CompareTo(deleted.ID) == 0 select item).ToList(); DBContext.Clients.Remove(list[0]); DBContext.SaveChanges(); this.ShowAll(); } else { MessageBox.Show("Не выбрано поле для удаления", "Ошибка"); } } catch (System.Data.SqlClient.SqlException) { MessageBox.Show("Нельзя удалить связанные записи", "Ошибка"); } }
public bool ThemThuoc(SANPHAM thuoc) { try { MyDBContext context = new MyDBContext(); thuoc.MaSP = autoID(); context.SANPHAMs.Add(thuoc); context.SaveChanges(); return(true); } catch { return(false); } }
public ActionResult Create(CustomerFormViewModel viewModel) { var membershipType = _Context.MembershipTypes.Single(x => x.Id == viewModel.MembershipTypeId); Customer customer = new Customer { Name = viewModel.Customer.Name, IsSubscribeToNewsLetter = viewModel.Customer.IsSubscribeToNewsLetter, MembershipType = membershipType, BirthDate = viewModel.Customer.BirthDate, }; _Context.Customers.Add(customer); _Context.SaveChanges(); return(RedirectToAction("Index", "Customer")); }
private void AddBtn_Click(object sender, RoutedEventArgs e) { var job = new DataUpdateJobDetails { Name = "NewJob", UseTag = true, Frequency = BarSize.OneDay, Time = new TimeSpan(8, 0, 0), WeekDaysOnly = true }; Jobs.Add(job); JobsGrid.SelectedItem = job; using (var context = new MyDBContext()) { context.DataUpdateJobs.Add(job); context.SaveChanges(); } }
public ActionResult Create(BulletList bullet) { try { //if (ModelState.IsValid) //{ MyDB.BulletLists.Add(bullet); MyDB.SaveChanges(); //} } catch { } return(PartialView()); }
public ActionResult Create(Paragraph paragraph) { try { //if (ModelState.IsValid) //{ MyDB.Paragraphs.Add(paragraph); MyDB.SaveChanges(); //} } catch { } return(PartialView()); }
public ActionResult Register(UserAccount account) { if (ModelState.IsValid) { using (MyDBContext db = new MyDBContext()) { db.userAccount.Add(account); db.SaveChanges(); } ModelState.Clear(); ViewBag.Message = account.FirstName + " " + account.LastName + " " + "Successfully Registered."; } return(View()); }
public ActionResult AddEvent(CalendarEventViewModel newEvent) { try { CalendarEventModel calendarEvent = new CalendarEventModel { title = newEvent.title, color = Enum.GetName(typeof(eventColor), newEvent.color), description = newEvent.description, start = newEvent.startDate.Date.ToString("yyyy-MM-dd") + "T" + newEvent.startTime + ":00", allDay = newEvent.allDay }; if (!calendarEvent.allDay) { calendarEvent.end = newEvent.endDate + "T" + newEvent.endTime + ":00"; } else { calendarEvent.end = null; } try { db.CalendarEventModels.Add(calendarEvent); db.SaveChanges(); } catch (Exception e) { Console.WriteLine(e.Message); } return(RedirectToAction("Index")); } catch (Exception e) { Console.WriteLine(e.Message); return(View()); } }
private void OnSave(int numToEdit = 0) { using (db = new MyDBContext()) { EnergyResource newER; foreach (EnergyResource er in ERList) { newER = db.EnergyResources.Find(er.Id); newER.Name = er.Name; newER.Unit = er.Unit; newER.IsMain = er.IsMain; } db.SaveChanges(); } }
public ActionResult Create(EmployeeModel em) { var viewmodel = new EmployeeViewModel(); if (ModelState.IsValid) { viewmodel.Name = em.Name; viewmodel.Email = em.Email; viewmodel.Age = em.Age; viewmodel.Branch_Id = em.Branch_Id; //var branchname = _defContext.branch.Where(r => r.Id == em.Branch_Id).FirstOrDefault().BranchNmae; //em.BranchName = branchname; var branch = _defContext.branch.Where(r => r.Id == em.Branch_Id).ToList(); viewmodel.BranchName = branch != null?branch.FirstOrDefault().BranchNmae : ""; viewmodel.Deptt_Id = em.Deptt_Id; viewmodel.Section_Id = em.Section_Id; _defContext.employee.Add(em); _defContext.SaveChanges(); return(RedirectToAction("Index")); } return(View(em)); }
public IActionResult SetCourse([FromQuery] Course cor) { Course new_cor = new Course { code = cor.code, name = cor.name, credit_hours = cor.credit_hours, type = cor.type }; _context.Add(new_cor); _context.SaveChanges(); return(Content("Changes Saved")); }
public ActionResult Registration([Bind(Exclude = "IsEmailVerified ,ActivationCode")] Entreprise entreprise) { bool Status = false; string message = ""; //Model if (ModelState.IsValid) { #region //Email mawjoud var isExist = IsEmailExist(entreprise.EmailID); if (isExist) { ModelState.AddModelError("EmailExist", "Email"); return(View(entreprise)); } #endregion #region Generate Activation Code entreprise.ActivationCode = Guid.NewGuid(); #endregion #region Password Hashng entreprise.Password = Crypto.Hash(entreprise.Password); entreprise.ConfirmPassword = Crypto.Hash(entreprise.ConfirmPassword); #endregion entreprise.IsEmailVerified = false; #region // Save in database using (MyDBContext db = new MyDBContext()) { db.DBSetEntreprise.Add(entreprise); db.SaveChanges(); // Send email to user SendVerificationLinkEmail(entreprise.EmailID, entreprise.ActivationCode.ToString()); message = "Registration successfuly done . Account activation link" + "has been sent to your email id : " + entreprise.EmailID; Status = true; } #endregion } else { message = "Invalid Request"; } ViewBag.Message = message; ViewBag.Status = Status; return(View(entreprise)); }
private void AddButton_Click(object sender, RoutedEventArgs e) { using (MyDBContext db = new MyDBContext()) { if (!String.IsNullOrWhiteSpace(PlaceBox.Text) && DateBox.SelectedDate.HasValue && TimeBox.Value.HasValue && ClientCombo.SelectedIndex != -1 && WorkerCombo.SelectedIndex != -1 && TransportCombo.SelectedIndex != -1 && TypeCombo.SelectedIndex != -1 ) { Order order = new Order { ID = db.Orders.Count() + 1, Place = PlaceBox.Text, Date = DateBox.SelectedDate.Value, Time = TimeBox.Value.Value, Client = GetClient(db.Clients.ToList()), Worker = GetWorker(db.Workers.ToList()), Order_Type = GetType(db.Order_Types.ToList()), Transport = GetTransport(db.Transports.ToList()) }; if (EditID == -1) { db.Orders.Add(order); } else { var result = db.Orders.Find(EditID); result.Place = PlaceBox.Text; result.Date = DateBox.SelectedDate.Value; result.Time = TimeBox.Value.Value; result.Client = GetClient(db.Clients.ToList()); result.Worker = GetWorker(db.Workers.ToList()); result.Order_Type = GetType(db.Order_Types.ToList()); result.Transport = GetTransport(db.Transports.ToList()); } } else { MessageBox.Show("Заполнены не все поля"); } db.SaveChanges(); } this.Close(); }
public ActionResult Add(Sach sach, HttpPostedFileBase fileUpload) { if (Session["User"] == null) { return(RedirectToAction("Login", "Login")); } else { ViewBag.MaChuDe = new SelectList(db.ChuDes.OrderBy(n => n.TenChuDe), "MaChuDe", "TenChuDe"); ViewBag.MaNXB = new SelectList(db.NhaXuatBans.OrderBy(n => n.MaNXB), "MaNXB", "TenNXB"); var model = new SachDao().CheckSach(sach.TenSach); if (model == false) { ViewBag.ThongBao = "Sách Đã Tồn Tại Trong Danh Sách Sách"; return(View("Add")); } else { if (fileUpload == null) { ViewBag.ThongBao = "Nhập Hình Ảnh"; return(View()); } if (ModelState.IsValid) { var fileName = Path.GetFileName(fileUpload.FileName); var path = Path.Combine(Server.MapPath("~/HinhAnhSP/"), fileName); if (System.IO.File.Exists(path)) { ViewBag.ThongBao = "Hình Ảnh Đã Tồn Tại"; return(View("Add")); } else { fileUpload.SaveAs(path); } sach.AnhBia = fileUpload.FileName; db.Saches.Add(sach); db.SaveChanges(); return(RedirectToAction("Index", "SachAD")); } } return(View("Index")); } }
public ActionResult Save(Customer customer) { if (customer.Id == 0) { _context.Customers.Add(customer); } else { var customerInDb = _context.Customers.Single(c => c.Id == customer.Id); customerInDb.name = customer.name; customerInDb.issubcribed = customer.issubcribed; customerInDb.demoId = customer.demoId; } _context.SaveChanges(); return(RedirectToAction("Index", "Customer")); }
private void buttonUpdateWeight_Click(object sender, EventArgs e) { WeightFactor cur = (WeightFactor)bindingSourceWeight.Current; using (MyDBContext db = new MyDBContext()) { var thisF = db.WeightFactors.Single(f => f.Id == cur.Id); thisF.Weight = Convert.ToInt32(txtWeight.Value); thisF.keyWord = txtToFind.Text; thisF.Dimension = comboBoxDim.Text; //db.WeightFactors.Attach(cur); db.SaveChanges(); comboBoxDim_SelectedIndexChanged(sender, e); } }
private static void createUserTable(MyDBContext context) { var ituser = context.User.Where(x => x.Login == "Sudalin"); if (ituser.Count() == 0) { var user = new User { Login = "******", Password = "******", Role = 9 }; context.User.Add(user); context.SaveChanges(); } }
private void btnUpdateDetail_Click(object sender, EventArgs e) { WeightFactorForDetail cur = (WeightFactorForDetail)bindingSourceDetail.Current; using (MyDBContext db = new MyDBContext()) { var thisF = db.WeightFactorForDetails.Single(f => f.Id == cur.Id); thisF.Weight = Convert.ToInt32(numericUpDownDetail.Value); thisF.keyWord = txtToFind.Text; thisF.NatureOfTnx = cbDetailFactor.Text; //db.WeightFactors.Attach(cur); db.SaveChanges(); cbDetailFactor_SelectedIndexChanged(sender, e); } }
public ActionResult Save(Customer customer) { if (customer.Id == 0) { _context.Customers.Add(customer); } else { var customerInDb = _context.Customers.Single(c => c.Id == customer.Id); customerInDb.Name = customer.Name; customerInDb.Birthdate = customer.Birthdate; customerInDb.MembershipTypeId = customer.MembershipTypeId; } _context.SaveChanges(); return(RedirectToAction("Index", "Customers")); }
public IActionResult InsertFaculty([FromQuery] Faculty fac) { Faculty new_fac = new Faculty { name = fac.name, phone = fac.phone, email = fac.email, address = fac.address, qualification = fac.qualification }; _context.Add(new_fac); _context.SaveChanges(); return(Content("Changes Saved")); }
public IActionResult Index() { myDBContext.Add(new Book() { Name = "三国演义", Content = "三国", AutherID = 1, DateTime = DateTime.Now }); myDBContext.SaveChanges(); ViewBag.Message = "OK!"; var list = myDBContext.Books; return(View(list)); }
public async Task <bool> Delete(Guid id) { _logger.LogDebug($"Calling delete Attachment for id=[{id}]"); var t = await this.GetInner(id); if (t != null && System.IO.File.Exists(t.FullPath)) { var directory = Path.GetDirectoryName(t.FullPath); Directory.Delete(directory, true); //File.Delete(t.FullPath); } t.XDeleteDate = DateTime.UtcNow; _dbCtx.Attachments.Update(t); _dbCtx.SaveChanges(); return(true); }
static void Main(string[] args) { //Add record using (var db = new MyDBContext()) { db.Templetes.Add(new Templete { Name = "Test111" }); db.Templetes.Add(new Templete { Name = "Test11" }); db.SaveChanges(); } //delete record from id using (var db = new MyDBContext()) { var del = db.Templetes.SingleOrDefault(x => x.Id == 1); if (del != null) { db.Templetes.Remove(del); db.SaveChanges(); } } //edit record using (var db = new MyDBContext()) { var edit = db.Templetes.SingleOrDefault(x => x.Id == 10); edit.Name = "UpdateName"; db.SaveChanges(); } //find using (var db = new MyDBContext()) { var find = db.Templetes.Where(x => x.Name == "UpdateName").FirstOrDefault(); Console.WriteLine("Find lines Id: " + find.Id); } //Writing using (var db = new MyDBContext()) { foreach (var templete in db.Templetes) { Console.WriteLine("Template {0} = {1}", templete.Id, templete.Name); } } Console.ReadKey(); }