public void Add(MedicalBills entity) { db.Attach(entity.MedicalBillsType); db.Attach(entity.Form); db.MedicalBills.Add(entity); db.SaveChanges(); }
public async Task <IActionResult> OnPostDeleteTypeAsync(int id) { var type = _context.Types.Include(e => e.Products).ToList().Find(it => it.Id == id); if (type.Parent != null) { var newParent = _context.Types.First(it => it.Id == type.Parent.Id); if (newParent.Products == null) { newParent.Products = new List <Product>(); } newParent.Products.AddRange(type.Products); List <Models.Product> products = _context.products.ToList().FindAll(it => it.Head?.Id == type.Id); if (products != null) { foreach (var item in products) { item.Head = newParent; _context.Attach(item).State = EntityState.Modified; } } newParent.Children.Remove(type); _context.Attach(newParent).State = EntityState.Modified; if (type.Children != null) { foreach (var item in type.Children) { item.Parent = newParent; _context.Attach(item).State = EntityState.Modified; } } } else { if (type.Children != null) { type.Children.ForEach(it => { it.Parent = null; _context.Attach(it).State = EntityState.Modified; }); } } if (type != null) { _context.Types.Remove(type); await _context.SaveChangesAsync(); } return(RedirectToPage()); }
public async Task <IActionResult> Put(Guid id, [FromBody] CompraRequest compraRequest) { if (!ModelState.IsValid) { return(BadRequest(ModelState.GetErrorMessages())); } var db = new ApplicationContext(); // TODO ver https://www.freecodecamp.org/news/an-awesome-guide-on-how-to-build-restful-apis-with-asp-net-core-87b818123e28/ // Aprender a usar a injeção de deéndências e o AutoMapper para melhorar o código no geral Compra compra = db.Compras.Find(id); //compra.Nome = compraRequest.Nome; //compra.Concluido = compraRequest.Concluido; //compra.Observacao = compraRequest.Observacao; try { //db.Compras.Update(compra); db.Attach(compra); db.Entry(compra).CurrentValues.SetValues(compraRequest); await db.SaveChangesAsync(); } catch (Exception ex) { return(BadRequest(ex.Message)); } // TODO - criar um objeto de resposta return(Ok("Objeto atualizado")); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } context.Attach(StorageRoom).State = EntityState.Modified; try { await context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!context.TStorageRoom.Any(g => g.idStorageRoom == StorageRoom.idStorageRoom)) { return(NotFound()); } else { throw; } } return(RedirectToPage("/StorageFacilities")); }
public async Task <int> UpdateAsync(LocationTemplate location) { _context.Attach(location).State = EntityState.Modified; int changes = await _context.SaveChangesAsync(); return(await Task.FromResult(changes)); }
private static void AtualizarDados() { using var dbContext = new ApplicationContext(); // var cliente = dbContext.Clientes.Find(1); // cliente.Nome = "Cliente diferente dnv"; var cliente = new Cliente { Id = 1, Telefone = "3199999999" }; dbContext.Attach(cliente); var clienteDesconectado = new { Nome = "Cliente desconectado a", Telefone = "1132658945" }; dbContext.Entry(cliente).CurrentValues.SetValues(clienteDesconectado); // Indica que todas as propriedades sofreram alterações. Quando comentado, o EF Core já sabe o que foi alterado porque a entidade é rastreada após o SELECT. // dbContext.Clientes.Update(cliente); dbContext.SaveChanges(); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } _context.Attach(Person).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!_context.People.Any(e => e.Id == Person.Id)) { return(NotFound()); } else { throw; } } return(RedirectToPage("Index")); }
private static void AtualizarDados() { using (var db = new ApplicationContext()) { //var cliente = db.Clientes.Find(1); //cliente.Nome = "Nome Cliente Alterado 01"; //db.Entry(cliente).State = EntityState.Modified; var clienteDesconectado = new { Nome = "Cliente desconectado 01", Telefone = "44564456" }; var cliente = new Cliente { Id = 1 }; db.Attach(cliente); db.Entry(cliente).CurrentValues.SetValues(clienteDesconectado); //db.Clientes.Update(cliente); db.SaveChanges(); } }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } context.Attach(Goods).State = EntityState.Modified; try { await context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!context.TGoods.Any(g => g.idGoods == Goods.idGoods)) { return(NotFound()); } else { throw; } } return(RedirectToPage("/WorkingGoods")); }
public async Task <int> UpdateAsync(Tag tag) { _context.Attach(tag).State = EntityState.Modified; int changes = await _context.SaveChangesAsync(); return(await Task.FromResult(changes)); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } Admin.Password = _encryption.HashPassword(Admin.Password); Admin.LastChanged = DateTime.UtcNow; _context.Attach(Admin).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AdminExists(Admin.Id)) { return(NotFound()); } else { throw; } } return(RedirectToPage("./Index")); }
private async Task CheckPriceAsync(Advert advert, ApplicationContext context) { var grabber = _grabbers.First(x => advert.Url.Contains(x.Url)); var freshAdvert = await grabber.ParseAdvert(advert.Url); if (freshAdvert.LowPrice != default && freshAdvert.LowPrice != advert.LowPrice) { await NotifyUserOfPriceCut(advert, freshAdvert, DateTime.Now); advert.LowPrice = freshAdvert.LowPrice; advert.LastCheckDate = DateTime.Now; context.Attach(advert); context.Entry(advert).State = EntityState.Modified; var priceHistory = new AdvertPriceHistory { AdvertId = advert.Id, Price = advert.LowPrice, ChangeDate = advert.LastCheckDate }; await context.AdvertPriceHistories.AddAsync(priceHistory); await context.SaveChangesAsync(); } }
public async Task <DailyAggregateCorporation> GetOrCreateDailyAggregateCorporation(Corporation corporation, DateTime date) { DailyAggregateCorporation aggregate = await GetDailyAggregateCorporation(corporation.Id, date); if (aggregate == null) { aggregate = new DailyAggregateCorporation { CorporationID = corporation.Id, TimeStamp = date }; context.Attach(aggregate); } return(aggregate); }
private static void AtualizarDados() { using var db = new ApplicationContext(); var cliente = db.Clientes.Find(1); //var cliente = new Cliente //{ // Id = 1 //}; var clienteDesconectado = new { Nome = "Cliente Desconectado 2", Telefone = "22132323" }; db.Attach(cliente); db.Entry(cliente).CurrentValues.SetValues(clienteDesconectado); //Desconectado //db.Entry(cliente).State = EntityState.Modified; //Rastreamento //db.Clientes.Update(cliente); db.SaveChanges(); }
public async Task <int> UpdateAsync(CharacterTemplate character) { _context.Attach(character).State = EntityState.Modified; int changes = await _context.SaveChangesAsync(); return(await Task.FromResult(changes)); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } _context.Attach(Firma).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!FirmaExists(Firma.Id)) { return(NotFound()); } else { throw; } } return(RedirectToPage("./Index")); }
public async Task Handle(Update command) { Gif gif = _mapper.Map <Update, Gif>(command); _db.Attach(gif); _db.Entry(gif).Property("Title").IsModified = true; await _db.SaveChangesAsync(); }
public async Task UpdateAsync(Tool entity) { _context.Attach(entity); _context.Entry(entity).Property(u => u.Name).IsModified = true; _context.Entry(entity).Property(u => u.Application).IsModified = true; await _context.SaveChangesAsync(); }
public void UpdateMovie(Entities.Movie movie) { if (movie == null) { return; } _context.Attach(movie); _context.Entry(movie).State = EntityState.Modified; }
public async Task UpdateAsync(Brand entity) { _context.Attach(entity); _context.Entry(entity).Property(u => u.Name).IsModified = true; _context.Entry(entity).Property(u => u.Info).IsModified = true; await _context.SaveChangesAsync(); }
public Entities.Owner UpdateOwner(Entities.Owner dbOwner, Entities.Owner owner) { _context.Attach(dbOwner); dbOwner.Name = owner.Name; dbOwner.Address = owner.Address; _context.SaveChanges(); return(dbOwner); }
public async Task <ActionResult <Employee> > Update(Employee value) { Employee employee = await db.Employees.FindAsync(value.ID); employee.Name = value.Name; db.Employees.Update(employee); db.Attach(employee).State = EntityState.Modified; await db.SaveChangesAsync(); return(new JsonResult(employee)); }
public async Task UpdateAsync(Equipment entity) { _context.Attach(entity); _context.Entry(entity).Property(u => u.BrandId).IsModified = true; _context.Entry(entity).Property(u => u.ToolId).IsModified = true; _context.Entry(entity).Property(u => u.Info).IsModified = true; _context.Entry(entity).Property(u => u.Price).IsModified = true; await _context.SaveChangesAsync(); }
public async Task <OperationResult> ImportTransactionsAsync(IFormFile formFile) { var result = await ReadTransactionsCsvFile(formFile); if (!result.Success) { return(result); } #region update if exists, insert if not // kind of upsert implementation var transactionsToAdd = new List <Transaction>(); foreach (var pendingTransaction in result.Model) { var foundTransaction = await _applicationContext.Transactions .Select(transaction => new Transaction { Id = transaction.Id, Status = transaction.Status }) .AsNoTracking() .FirstOrDefaultAsync(transaction => transaction.Id == pendingTransaction.Id); if (foundTransaction == null) { var foundClientId = await _applicationContext.Clients .Where(client => client.Name == pendingTransaction.Client.Name) .Select(client => client.Id) .FirstOrDefaultAsync(); if (foundClientId > 0) { pendingTransaction.ClientId = foundClientId; pendingTransaction.Client = null; } transactionsToAdd.Add(pendingTransaction); } else { _applicationContext.Attach(foundTransaction); foundTransaction.Status = pendingTransaction.Status; } } await _applicationContext.Transactions.AddRangeAsync(transactionsToAdd); await _applicationContext.SaveChangesAsync(); #endregion return(new OperationResult(true)); }
public async Task <IActionResult> Edit(Product product, ItemViewModel prod) { byte[] imageData = null; if (prod.Image != null) { using var binaryReader = new BinaryReader(prod.Image.OpenReadStream()); imageData = binaryReader.ReadBytes((int)prod.Image.Length); } product.Image = imageData; product.startCol = prod.Col; db.Attach(product).State = EntityState.Modified; await db.SaveChangesAsync(); return(RedirectToAction("Index")); }
public async Task UpdateUserState(int id, UserState state) { using (var context = new ApplicationContext()) { var user = new UserInfo { UserInfoId = id, State = state }; context.Attach(user); context.Entry(user).Property(u => u.State).IsModified = true; await context.SaveChangesAsync(); } }
/// <summary> /// Faz o Update apenas com o campo que foi alterado sem a necessidade de consultar o objeto no banco /// </summary> private static void AtualizarApenasOsCamposAlterados2() { var db = new ApplicationContext(); var cliente = new Cliente() { Id = 1, }; var clienteDesconectado = new { Nome = "Daniel4" }; db.Attach(cliente); db.Entry(cliente).CurrentValues.SetValues(clienteDesconectado); db.SaveChanges(); }
private static void AtualizarDados() { using var db = new ApplicationContext(); var cliente = new Cliente { Id = 1 }; var clienteDesconectado = new { Nome = "Cliente Desconectado Passo 3", Telefone = "36051526" }; db.Attach(cliente); db.Entry(cliente).CurrentValues.SetValues(clienteDesconectado); db.SaveChanges(); }
public IActionResult AlteraDadosSimples([FromBody] MudaPerfilDTO mudancas) { if (User.Identity.Name != null) { string email = User.Identity.Name; var usuario = _ctx.Usuarios.Where(u => u.Email.Equals(email)).FirstOrDefault(); usuario.Celular = mudancas.Celular; usuario.Nome = mudancas.Nome; _ctx.Attach(usuario).State = EntityState.Modified; _ctx.SaveChanges(); return(Ok()); } else { return(Unauthorized()); } }
private static void AtualizarDadosDesconectados() { using var db = new ApplicationContext(); // var cliente = db.Clientes.Find(1); var cliente = new Cliente { Id = 1 }; // Objeto anônimo var clienteDesconectado = new { Cep = "80420010", Cidade = "Curitiba" }; db.Attach(cliente); db.Entry(cliente).CurrentValues.SetValues(clienteDesconectado); db.SaveChanges(); }