public async Task <ApiResult <List <AdminMemberDto> > > UpdateMemberForAdmin(AdminMemberDto dto) { try { var member = await _context.Members.FirstOrDefaultAsync(m => m.Id == dto.Id); // TODO: update identity account username before updating the rest of member information await UpdateMemberPropertiesForAdmin(dto, member); // detach all positions to prevent duplicate entity tracking error when saving foreach (var position in dto.Positions) { _context.Entry(position).State = EntityState.Detached; } await _context.SaveChangesAsync(); var result = await GetMembers <AdminMemberDto>(); return(result); } catch (Exception ex) { _logger.LogError("An issue occured when trying to update a member: \n" + ex.Message + "\n\nStack Trace: \n" + ex.StackTrace); return(new ApiResult <List <AdminMemberDto> > { Successful = false, Error = "An issue occured when trying to update a member." }); } }
public void AddQuestion(Question question) { _appContext.Questions.Add(question); _appContext.Entry(question.Sign).State = EntityState.Unchanged; _appContext.Entry(question.Sign.Type).State = EntityState.Unchanged; _appContext.SaveChanges(); }
public virtual void Delete <TEntity>(TEntity entityToDelete) where TEntity : class { if (context.Entry(entityToDelete).State == EntityState.Detached) { context.Set <TEntity>().Attach(entityToDelete); } context.Set <TEntity>().Remove(entityToDelete); }
public virtual void Delete(TEntity entityToDelete) { if (context.Entry(entityToDelete).State == EntityState.Detached) { dbSet.Attach(entityToDelete); } dbSet.Remove(entityToDelete); }
public long Insert(OrderModel model) { var orderDetails = new List <OrderDetail>(); foreach (var item in model.OrderDetails) { var orderDetail = new OrderDetail { ProductId = item.ProductId, Quantity = item.Quantity, TotalMoney = item.TotalMoney, CreateBy = item.CreateBy, CreatedDate = item.CreatedDate, LastModifiedBy = item.LastModifiedBy }; orderDetails.Add(orderDetail); } var orderEntity = new Order { OrderDetails = orderDetails, IsCharged = false, UserId = model.UserId, Total = model.OrderDetails.Sum(x => x.Cost), LastModifiedBy = model.LastModifiedBy, CreateBy = model.CreateBy, CreatedDate = model.CreatedDate, OrderCode = model.OrderCode, CodeDiscount = model.CodeDiscount, TotalMoney = model.TotalMoney, Discount = model.Discount, Quantity = model.Quantity, PointUsed = model.PointUsed, IsSendToGhn = model.IsSendToGhn, ServiceId = model.ServiceId, Phone = model.Phone, Address = model.Address, FullName = model.FullName, Note = model.Note }; var user = _context.Users.FirstOrDefault(x => x.Id == model.UserId); if (user != null) { user.OrderCount++; _context.Entry(user).State = EntityState.Modified; } _context.Orders.Add(orderEntity); if (_context.SaveChanges() > 0) { return(_context.Orders.Max(x => x.Id)); } return(0); }
public void FinishUserTest(Test test) { foreach (var stat in test.Stats) { _appContext.Entry(stat.Question.Sign).State = EntityState.Unchanged; _appContext.Entry(stat.Question.Sign.Type).State = EntityState.Unchanged; } _appContext.Tests.Update(test); _appContext.SaveChanges(); }
public async Task UpdateAsync(TEntity entity) { EntityEntry <TEntity> entry; var objToUpdate = await _dbSet.FindAsync(entity.Id); entry = _dbContext.Entry(objToUpdate); entry.CurrentValues.SetValues(entity); entry.State = EntityState.Modified; _dbContext.SaveChanges(); }
internal void UpdateInfo(EditInfo2B2ViewModel info) { var lsp = db.NhaCungCaps.Find(info.MaNCC); lsp.TenNCC = info.TenNCC; lsp.DiaChi = info.DiaChi; lsp.SDT_NCC = info.SDT_NCC; lsp.Email = info.Email; db.Entry(lsp).State = EntityState.Modified; db.SaveChanges(); }
public ActionResult Edit(CrudHistoricalSightVm model, Address address) { try { model.HistoricalSight.Address = address; model.HistoricalSight.Address.SetCoordinates(address.LatitudeString, address.LongitudeString); if (model.HistoricalSight.Logo == null || model.LogoFile != null) { model.HistoricalSight.Logo = FileUpload.GetBytes(model.LogoFile, "Logo"); } if (model.HistoricalSight.Cover == null || model.CoverFile != null) { model.HistoricalSight.Cover = FileUpload.GetBytes(model.CoverFile, "Capa"); } ModelState.Remove("HistoricalSight.Logo"); ModelState.Remove("HistoricalSight.Cover"); if (!ModelState.IsValid) { SetBiewBags(model); return(View(model).Error(ModelState)); } var oldHistoricalSight = _db.HistoricalSights .Include(c => c.Address) .FirstOrDefault(x => x.HistoricalSightId == model.HistoricalSight.HistoricalSightId); if (oldHistoricalSight == null) { return(RedirectToAction("Index").Success("Memorial atualizado com sucesso")); } _db.Entry(oldHistoricalSight).CurrentValues.SetValues(model.HistoricalSight); oldHistoricalSight.Address.UpdateAddress(model.HistoricalSight.Address); _db.Entry(oldHistoricalSight.Address).State = EntityState.Modified; _db.SaveChanges(); return(RedirectToAction("Index").Success("Memorial atualizado com sucesso")); } catch (Exception ex) { SetBiewBags(model); return(View(model).Error(ex.Message)); } }
public ActionResult Edit(CrudEventVm model, AddressForEventVm address) { try { model.Address = address; model.Event.Address = model.GetAddress(address); model.Event.Address.SetCoordinates(address.LatitudeString, address.LongitudeString); if (model.Event.Logo == null || model.LogoFile != null) { model.Event.Logo = FileUpload.GetBytes(model.LogoFile, "Logo"); } if (model.Event.Cover == null || model.CoverFile != null) { model.Event.Cover = FileUpload.GetBytes(model.CoverFile, "Capa"); } ModelState.Remove("Event.Logo"); ModelState.Remove("Event.Cover"); if (!ModelState.IsValid) { SetBiewBags(model); return(View(model).Error(ModelState)); } var oldCompany = _db.Events .Include(c => c.Address) //.Include(c => c.Contacts) .FirstOrDefault(x => x.EventId == model.Event.EventId); if (oldCompany == null) { return(RedirectToAction("Index").Success("Empresa atualizada com sucesso")); } // Update parent _db.Entry(oldCompany).CurrentValues.SetValues(model.Event); oldCompany.Address.UpdateAddress(model.Event.Address); _db.Entry(oldCompany.Address).State = EntityState.Modified; _db.SaveChanges(); return(RedirectToAction("Index")); } catch (Exception ex) { SetBiewBags(model); return(View(model).Error(ex.Message)); } }
public ActionResult Edit([Bind(Include = "ID,PostTitle,PostAuthor,PostTags,PostText,TitlePic,EditDate")] BlogPosts posts) { if (ModelState.IsValid) { String aDate = DateTime.UtcNow.ToString("yyMMddHHmmss"); posts.EditDate = aDate; int aId = posts.ID; db.Entry(posts).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Details", new { id = aId })); } return(View(posts)); }
public void RemoveCompanyRoleState_Succeeds() { var companyGuid = Guid.NewGuid(); const string companyName = "Cool Company"; var roleGuid = Guid.NewGuid(); const string roleName = "Software Developer 2"; var inMemoryDatabaseBuilder = new InMemoryDatabaseBuilder(); var options = inMemoryDatabaseBuilder .WithCompanyState(companyGuid, companyName) .WithCompanyRoleState(roleGuid, roleName, companyGuid) .Build("GetCompanyState", true); // Run the test against a clean instance of the context using (var context = new MainContext(options)) { inMemoryDatabaseBuilder.InitializeContext(context); var sut = new MainRepository(context); sut.RemoveRoleFromCompanyState(companyGuid, roleGuid); var companyState = sut.GetCompanyState(companyGuid); var roleState = companyState.CompanyRoleStates.SingleOrDefault(w => w.Guid == roleGuid); roleState = context.CompanyRoleStates.Find(roleGuid); Assert.Equal(EntityState.Deleted, context.Entry(roleState).State); Assert.Equal(roleName, roleState.Name); } }
public async Task <bool> Update(Group group) { var groupEntity = await _context.Groups.FirstOrDefaultAsync(g => g.Id == group.Id); _context.Entry(groupEntity).CurrentValues.SetValues(group); return((await _context.SaveChangesAsync()) > 0); }
public async Task <IActionResult> PutAccountSettings(int id, AccountSettings accountSettings) { if (id != accountSettings.Id) { return(BadRequest()); } _context.Entry(accountSettings).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AccountSettingsExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public bool InsertOrUpdate(CategoryModel categoryModel) { try { var existedCategory = _context.Categories .Where(x => x.Id == categoryModel.Id && x.CategoryName == categoryModel.CategoryName).SingleOrDefault(); if (existedCategory != null) { existedCategory.CategoryName = categoryModel.CategoryName; existedCategory.Type = categoryModel.Type; existedCategory.LastModifiedBy = categoryModel.LastModifiedBy; if (categoryModel.Image != null) { //get the file's name var type = categoryModel.Image.ContentType; //get the bytes from the content stream of the file var thePictureAsBytes = new byte[categoryModel.Image.ContentLength]; using (BinaryReader theReader = new BinaryReader(categoryModel.Image.InputStream)) { thePictureAsBytes = theReader.ReadBytes(categoryModel.Image.ContentLength); } existedCategory.ImagePic = thePictureAsBytes; existedCategory.ImageType = type; } _context.Entry(existedCategory).State = EntityState.Modified; } else { //get the file's name string type = categoryModel.Image.ContentType; //get the bytes from the content stream of the file byte[] thePictureAsBytes = new byte[categoryModel.Image.ContentLength]; using (BinaryReader theReader = new BinaryReader(categoryModel.Image.InputStream)) { thePictureAsBytes = theReader.ReadBytes(categoryModel.Image.ContentLength); } var categoryEnity = new Category { CreatedDate = DateTime.Now, CreateBy = categoryModel.CreateBy, Type = categoryModel.Type, CategoryName = categoryModel.CategoryName, ImagePic = categoryModel.ImagePic, ImageType = type }; _context.Categories.Add(categoryEnity); } return(_context.SaveChanges() > 0); } catch (Exception) { throw; } }
public async Task <IActionResult> PutTodoItem(int id, BatteryItems batteryItems) { if (id != batteryItems.id) { return(BadRequest()); } _context.Entry(batteryItems).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BatteryExists(id)) { return(NotFound()); } else { throw; } } return(Ok(batteryItems)); // You can create or update data through postman with this put method. }
public async Task <IActionResult> PutTodoItem(int id, InterventionItems interventionItems) { if (id != interventionItems.id) { return(BadRequest()); } _context.Entry(interventionItems).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!InterventionExists(id)) { return(NotFound()); } else { throw; } } return(Ok(interventionItems)); }
public void RemoveProjectRoleState_Succeeds() { var projectGuid = Guid.NewGuid(); const string projectName = "Cool Project"; var roleGuid = Guid.NewGuid(); const string roleName = "Tester"; var inMemoryDatabaseBuilder = new InMemoryDatabaseBuilder(); var options = inMemoryDatabaseBuilder .WithProjectState(projectGuid, projectName) .WithProjectRoleState(roleGuid, roleName, projectGuid) .Build("GetProjectState", true); // Run the test against a clean instance of the context using (var context = new MainContext(options)) { inMemoryDatabaseBuilder.InitializeContext(context); var sut = new MainRepository(context); sut.RemoveRoleFromProjectState(projectGuid, roleGuid); var projectState = sut.GetProjectState(projectGuid); var roleState = projectState.ProjectRoleStates.SingleOrDefault(w => w.Guid == roleGuid); //Assert.Null(roleState); inconsistent testbehavior vs CompanyRole roleState = context.ProjectRoleStates.Find(roleGuid); Assert.Equal(EntityState.Deleted, context.Entry(roleState).State); Assert.Equal(roleName, roleState.Name); } }
public async Task <IActionResult> PutRequerente(int id, Requerente requerente) { if (id != requerente.Id) { return(BadRequest()); } _context.Entry(requerente).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!RequerenteExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <ActionResult <Purchase> > PutPurchase(int id, Purchase purchase) { if (id != purchase.Id) { return(BadRequest()); } _context.Entry(purchase).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PurchaseExists(id)) { return(NotFound()); } else { throw; } } return(purchase); }
public async Task <IActionResult> PutUserModel(UserModel userModel) { if (Int32.Parse(User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value) != userModel.Id) { return(BadRequest()); } userModel.Password = _encrypter.EncryptData(userModel.Password); _context.Entry(userModel).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!UserModelExists(Int32.Parse(User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value))) { return(NotFound()); } else { throw; } } return(Ok(userModel)); }
public async Task <IActionResult> PutAddressModel(int id, AddressModel addressModel) { if (id != addressModel.Id) { return(BadRequest()); } _context.Entry(addressModel).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AddressModelExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <ActionResult <Stock> > PutStock(int id, Stock stock) { if (id != stock.Id) { return(BadRequest()); } _context.Entry(stock).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!StockExists(id)) { return(NotFound()); } else { throw; } } return(stock); }
public bool InsertOrUpdate(ResourceModel resModel) { var existedResource = _context.Resources.Where(x => x.Id == resModel.Id).FirstOrDefault(); if (existedResource != null) { existedResource.Name = resModel.Name; existedResource.Value = resModel.Value; _context.Entry(existedResource).State = EntityState.Modified; } else { var resourceEntity = new Resource { CreateBy = resModel.CreateBy, CreatedDate = DateTime.Now, LastModifiedBy = resModel.LastModifiedBy, Culture = resModel.Culture, Name = resModel.Name, Value = resModel.Value }; _context.Resources.Add(existedResource); } return(_context.SaveChanges() > 0); }
[HttpPut("{id}")] // We can add a lead to the database through postman and the put method. public async Task <IActionResult> PutTodoItem(int id, LeadItems leadItems) { if (id != leadItems.id) { return(BadRequest()); } _context.Entry(leadItems).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!LeadExists(id)) { return(NotFound()); } else { throw; } } return(Ok(leadItems)); // The code above will either create a new lead or update one. It also // confirms that a lead won't be posted twice. }
public IHttpActionResult PutProveedor(int id, Proveedor proveedor) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != proveedor.Id) { return(BadRequest()); } db.Entry(proveedor).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!ProveedorExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public void BalanceContacts(User oldUser, User newUser, MainContext ctx) { var ids = oldUser.Contacts.Select((t, i) => oldUser.Contacts.ElementAt(i).ContactId).ToList(); ctx.Contacts.RemoveRange(oldUser.Contacts.Where(x => ids.Any(e => e == x.ContactId))); if (newUser.Contacts == null) { return; } foreach (var item in newUser.Contacts) { if (oldUser.Contacts == null) { continue; } var x = oldUser.Contacts.FirstOrDefault(s => s.ContactId == item.ContactId && s.ContactId != Guid.Empty && item.ContactId != Guid.Empty); if (x != null) { x.Atualizar(item); ctx.Entry(x).CurrentValues.SetValues(item); } else { oldUser.Contacts.Add(item); } } }
public async Task <bool> Update(Event ev) { var res = await _context.Events.FirstOrDefaultAsync(e => e.Id == ev.Id); _context.Entry(res).CurrentValues.SetValues(ev); return((await _context.SaveChangesAsync()) > 0); }
public async Task <IActionResult> PutQueueEntryModel([FromRoute] int id, [FromBody] QueueEntryModel queueEntryModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != queueEntryModel.QueueId) { return(BadRequest()); } _context.Entry(queueEntryModel).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!QueueEntryModelExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> PutTodoItem(int id, ElevatorItems elevatorItems) { if (id != elevatorItems.id) { return(BadRequest()); } _context.Entry(elevatorItems).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ElevatorExists(id)) { return(NotFound()); } else { throw; } } return(Ok(elevatorItems)); // This is where we set our put method, you can add elevators // to the database through postman. }
public void DeleteTournament(int id) { var tournament = GetTournament(id); using (var context = new MainContext()) { context.Entry(tournament).State = EntityState.Deleted; context.SaveChanges(); } }
public void DeleteUser(int id) { var user = GetUser(id); using (var context = new MainContext()) { context.Entry(user).State = EntityState.Deleted; context.SaveChanges(); } }