public async Task <IActionResult> PutPerson([FromRoute] int id, [FromBody] Person person) { if (id != person.Id) { return(BadRequest()); } _context.Entry(person).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PersonExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public void Add(string name, string position, int tableNumber, string order, int managerTableNumber) { var manager = new Person(); if (managerTableNumber != 0) { manager = Context.Persons.Single(p => p.TableNumber == managerTableNumber); } else { manager = null; } var person = new Person { Name = name, Position = position, TableNumber = tableNumber, Order = order, Manager = manager, IsRemoved = false }; Context.Entry(person).State = EntityState.Added; Context.SaveChanges(); }
public ActionResult CreateNewCredit(int id, int Credit, int Ammount) { Credit credit = context.Credit.Where(c => c.CreditID == Credit).FirstOrDefault(); ClientsCredit lastDeposit = context.ClientsCredit.ToList().LastOrDefault(); String num = lastDeposit.ClientCreditNumber.Substring(lastDeposit.ClientCreditNumber.Length - 9); int depNum = int.Parse(num); depNum++; num = depNum.ToString(); while (num.Length != 9) { num = "0" + num; } ClientsCredit newCredit = new ClientsCredit(); newCredit.ClientID = id; newCredit.Active = true; newCredit.CreditID = Credit; newCredit.DateStart = DateTime.Today; newCredit.DateEnd = DateTime.Today.AddMonths(credit.Period); newCredit.Period = credit.Period; newCredit.Amount = Ammount; newCredit.Diff = credit.Diff; newCredit.ClientCreditNumber = credit.BalanceId.ToString() + num;; newCredit.Period = credit.Period; context.ClientsCredit.Add(newCredit); Currency currency = context.Currency.Where(c => c.CurrencyID == credit.CurrencyID).FirstOrDefault(); ClientsDeposit Fond = context.ClientsDeposits.Where(d => d.ClientID == 0).FirstOrDefault(); ClientsDeposit fond = Fond; fond.Amount = Fond.Amount - newCredit.Amount * currency.Value; context.Entry(Fond).CurrentValues.SetValues(fond); context.SaveChanges(); InterestCredit interestCredit = new InterestCredit { ClientsCreditID = newCredit.ClientsCreditID, InterestCreditNumber = "6660" + num, Active = true, Amount = newCredit.Amount * (credit.Percent * credit.Period / 12) / 100 + newCredit.Amount, PayMonths = 0, Period = credit.Period }; if (newCredit.Diff) { interestCredit.MonthlyPayment = (interestCredit.Amount - newCredit.Amount) / (interestCredit.Period - 1); interestCredit.LastMonthlyPayment = newCredit.Amount; } else { interestCredit.MonthlyPayment = interestCredit.Amount / interestCredit.Period; interestCredit.LastMonthlyPayment = interestCredit.MonthlyPayment; } context.InterestCredit.Add(interestCredit); context.SaveChanges(); return(Json(new AjaxResponse(new AjaxResponse()))); }
public async Task <IActionResult> PutPerson([FromRoute] int id, [FromBody] Person person) { if (id != person.Id) { _logger.LogWarning("ID {id} does not equal person ID", id); return(BadRequest()); } _context.Entry(person).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PersonExists(id)) { _logger.LogWarning("Could not put person with ID {id}", id); return(NotFound()); } else { throw; } } _logger.LogInformation("Put person with ID {id}", id); return(NoContent()); }
public virtual void Delete(TEntity entityToDelete) { if (context.Entry(entityToDelete).State == EntityState.Detached) { dbSet.Attach(entityToDelete); } dbSet.Remove(entityToDelete); }
public JsonResult Post(long id, [FromBody] Person person) { var oldPerson = db.Persons.Include(pn => pn.skills).FirstOrDefault(pn => pn.id == id); person.id = id; if (oldPerson != null) { if (validator.validatePerson(person)) { try { string oldData = ConstructPersonString(oldPerson); db.Skills.RemoveRange(oldPerson.skills); db.SaveChanges(); db.Entry(oldPerson).State = EntityState.Detached; db.Entry(person).State = EntityState.Modified; foreach (var skill in person.skills) { skill.person = person; db.Skills.Add(skill); } db.Update(person); db.SaveChanges(); var newPerson = db.Persons.Include(pn => pn.skills).FirstOrDefault(pn => pn.id == id); _logger.LogInformation($"success POST/PERSON/{id}"); _logger.LogInformation($"old data: {oldData}"); _logger.LogInformation($"new data: {ConstructPersonString(newPerson)}"); return(new JsonResult(newPerson) { StatusCode = StatusCodes.Status200OK }); } catch (DbUpdateException e) { _logger.LogError(e, $"InternalServerError POST/PERSON/{id}"); return(errorController.InternalError500(e.Message)); } } else { _logger.LogWarning($"bad request POST/PERSON/{id}"); return(errorController.BadRequest400()); } } else { _logger.LogWarning($"not found POST/PERSON/{id}"); return(errorController.NotFound404()); } }
private static void Upadte01(PersonContext ctx) { Person person = ctx.People.FirstOrDefault(); Console.WriteLine("Person:" + ctx.Entry(person).State); person.FirstName = "aa"; ctx.People.Update(person); Console.WriteLine("JobData:" + ctx.Entry(person).State); Console.WriteLine("ok"); Console.ReadLine(); }
/// <summary> /// Asynchronously gets an entity based on the supplied id. /// </summary> /// <param name="id">The id/key of the entity to be returned.</param> /// <returns>The entity with the matching id if one exists; otherwise null.</returns> public virtual Task <TEntity> GetByIDAsync(TKey id) { var result = _dbSet.FindAsync(id); // If a valid object is returned, we want to stop tracking it (in other words, detach it). // If we kept tracking it, then subsequent calls to the repository in the controller would fail. if (result.Result != null) { _context.Entry(result.Result).State = EntityState.Detached; } return(result); }
public async Task <IActionResult> PutPerson(int code, Person person) { try { if (code != person.Code) { return(BadRequest()); } _context.Entry(person).State = EntityState.Modified; await _context.SaveChangesAsync(); return(CreatedAtAction( nameof(GetPerson), new { code = person.Code, person }, person )); } catch (DbUpdateConcurrencyException) when(!PersonExists(code)) { return(NotFound()); } catch (System.Exception) { return(UnprocessableEntity()); } }
public ActionResult Change(Person person) { db.Entry(person).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); }
public void Marry(int personId, int spouseId) { var person1 = GetPersonById(personId); var person2 = GetPersonById(spouseId); person1.SpouseId = spouseId; person1.SpouseName = person2.FirstName; person2.SpouseId = personId; person2.SpouseName = person1.FirstName; _context.Entry(person1).State = EntityState.Modified; _context.Entry(person2).State = EntityState.Modified; _context.SaveChanges(); }
public IHttpActionResult PutReward(int id, Reward reward) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != reward.Id) { return(BadRequest()); } db.Entry(reward).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (db.Rewards.Find(id) == null) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public ActionResult UpdatePerson(long id, Person person) { if (id != person.Id) { BadRequest(); } if (person.Skills.Where(s => s.Id == 0).Any()) { _db.Skills.AddRange(person.Skills.Where(s => s.Id == 0)); } if (person.Skills.Where(s => s.Id != 0).Any()) { _db.Skills.UpdateRange(person.Skills.Where(s => s.Id != 0)); } var skills = _db.Skills.Where(s => s.PersonId == id).ToList(); var skillsToDelete = skills.Where(s => !person.Skills.Contains(s)); if (skillsToDelete.Any()) { _db.Skills.RemoveRange(skillsToDelete); } _db.Entry(person).State = EntityState.Modified; _db.SaveChanges(); return(NoContent()); }
private static void TrackGraph() { var ctx = new PersonContext(); var ctx2 = new PersonContext(); var person = ctx2.People.Include(c => c.JobData).Include(c => c.Contacts).FirstOrDefault(); ctx.ChangeTracker.TrackGraph(person, c => { switch (c.Entry.Entity) { case Person p: ctx.Entry(person).State = EntityState.Unchanged; Console.WriteLine("Person:" + p.PersonId); break; case JobData j: Console.WriteLine("Person:" + j.JobDataId); break; case Contact cc: Console.WriteLine("Person:" + cc.ContactId); break; default: break; } }); Console.ReadLine(); }
public IHttpActionResult PutContactType(int id, ContactType contactType) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != contactType.Id) { return(BadRequest()); } db.Entry(contactType).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!ContactTypeExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
// PUT api/Place/5 public HttpResponseMessage PutPlace(int id, Place place) { if (!ModelState.IsValid) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } if (id != place.Id) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } db.Entry(place).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex)); } return(Request.CreateResponse(HttpStatusCode.OK)); }
public ActionResult Edit([Bind(Include = "Id,Name,Birthdate,Age")] Person person, int[] selectedRewards, HttpPostedFileBase uploaded) { Person newPerson = db.Persons.Find(person.Id); newPerson.Name = person.Name; newPerson.Birthdate = person.Birthdate; newPerson.Age = person.Age; newPerson.Rewards.Clear(); if (selectedRewards != null) { //получаем выбранные rewards foreach (var c in db.Rewards.Where(co => selectedRewards.Contains(co.Id))) { newPerson.Rewards.Add(c); } } if (uploaded != null && uploaded.ContentLength > 0) { newPerson.Photo = new Image(); newPerson.Photo.ImageName = uploaded.FileName; newPerson.Photo.ContentType = uploaded.ContentType; newPerson.Photo.Content = new byte[uploaded.ContentLength]; uploaded.InputStream.Read(newPerson.Photo.Content, 0, uploaded.ContentLength); } db.Entry(newPerson).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); }
// PUT api/Place/5 public async Task <IHttpActionResult> PutPlace(int id, Place place) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != place.Id) { return(BadRequest()); } db.Entry(place).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PlaceExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public async Task <ActionResult <Person> > PutPerson(Guid id, Person person) { if (id != person.Id) { return(BadRequest()); } _context.Entry(person).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PersonExists(id)) { return(NotFound()); } else { throw; } } return(await GetPerson(id)); }
//пользователи для добавления в бан public string Array(BanPerson ban) { var clientList = ban.BanIdMassive.ToList(); // id клиентов для блокировки var userList = db.Users.ToList(); //все пользователи List <Person> banList = new List <Person>(); // список клиентов для блокировки foreach (var i in clientList) { foreach (var j in userList) { if (i == j.Id) { banList.Add(j); } } } foreach (var x in banList) { if (x != null) { x.Ban = true; x.BanDateTime = DateTime.Now; db.Entry(x).State = EntityState.Modified; db.SaveChanges(); } } return("Блокировка установлена"); }
public async Task <IActionResult> PutEmail([FromRoute] int id, [FromBody] Email email) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != email.EmailId) { return(BadRequest()); } _context.Entry(email).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!EmailExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public IHttpActionResult PutPerson(int id, [Bind(Include = "PersonID, FirstName, LastName, StreetAddress, City, State, Zip, Age, Interests, PhotoPath")] Person person) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != person.PersonID) { return(BadRequest()); } db.Entry(person).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!PersonExists(id)) { return(NotFound()); } else { throw; } } return(Content(HttpStatusCode.Accepted, person)); }
public ActionResult Edit([Bind(Include = "Id,Title,Description")] Reward reward, HttpPostedFileBase uploaded) { if (ModelState.IsValid) { Reward newReward = db.Rewards.Find(reward.Id); newReward.Description = reward.Description; newReward.Title = reward.Title; if (uploaded != null && uploaded.ContentLength > 0) { newReward.Image = new Image(); newReward.Image.ImageName = uploaded.FileName; newReward.Image.ContentType = uploaded.ContentType; newReward.Image.Content = new byte[uploaded.ContentLength]; uploaded.InputStream.Read(newReward.Image.Content, 0, uploaded.ContentLength); } if (User.IsInRole("candidateAdmin")) { GetTempChange().AddItem(reward, "Edit"); } else { db.Entry(newReward).State = EntityState.Modified; db.SaveChanges(); } return(RedirectToAction("Index")); } return(View(reward)); }
public int Edit(PersonEntity personEntity) { personContext.Entry(personEntity).State = EntityState.Modified; var rowsAffected = personContext.SaveChanges(); Validataors.ObjectValidator.ValidateRowsAffected(rowsAffected); return(rowsAffected); }
public ActionResult Edit(Client client) { Client Client = context.Clients.Where(c => c.ClientID == client.ClientID).First(); context.Entry(Client).CurrentValues.SetValues(client); context.SaveChanges(); ViewBag.Clients = Client; return(Json(new AjaxResponse(new AjaxResponse()))); }
public void UpdatePerson(Person person) { var entry = _dbContext.Persons.First(e => e.Id == person.Id); _dbContext.Entry(entry).CurrentValues.SetValues(person); //_dbContext.Entry(person).State = EntityState.Modified; Save(); }
public void EditPerson(Person person, Person newPerson) { // This might be entirely unnecessary, but I just wanted to try doing this with reflection foreach (var prop in person.GetType().GetProperties()) { prop.SetValue(person, prop.GetValue(newPerson)); } context.Entry(person).State = EntityState.Modified; context.SaveChanges(); }
public ActionResult Edit([Bind(Include = "Id,FirstName,LastName")] Person person) { if (ModelState.IsValid) { db.Entry(person).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(person)); }
public ActionResult Edit(Person person) { if (ModelState.IsValid) { db.Entry(person).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(person)); }
public ActionResult Edit([Bind(Include = "Id,Name,Age,PostalCode,Gender,BirthDate")] PersonModel personModel) { if (ModelState.IsValid) { db.Entry(personModel).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(personModel)); }
public static void Run() { // Ensure database is created and has a person in it using (var context = new PersonContext()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); context.People.Add(new Person { FirstName = "John", LastName = "Doe" }); context.SaveChanges(); } using (var context = new PersonContext()) { // Fetch a person from database and change phone number var person = context.People.Single(p => p.PersonId == 1); person.PhoneNumber = "555-555-5555"; // Change the persons name in the database (will cause a concurrency conflict) context.Database.ExecuteSqlCommand("UPDATE dbo.People SET FirstName = 'Jane' WHERE PersonId = 1"); try { // Attempt to save changes to the database context.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { foreach (var entry in ex.Entries) { if (entry.Entity is Person) { // Using a NoTracking query means we get the entity but it is not tracked by the context // and will not be merged with existing entities in the context. var databaseEntity = context.People.AsNoTracking().Single(p => p.PersonId == ((Person)entry.Entity).PersonId); var databaseEntry = context.Entry(databaseEntity); foreach (var property in entry.Metadata.GetProperties()) { var proposedValue = entry.Property(property.Name).CurrentValue; var originalValue = entry.Property(property.Name).OriginalValue; var databaseValue = databaseEntry.Property(property.Name).CurrentValue; // TODO: Logic to decide which value should be written to database // entry.Property(property.Name).CurrentValue = <value to be saved>; // Update original values to entry.Property(property.Name).OriginalValue = databaseEntry.Property(property.Name).CurrentValue; } } else { throw new NotSupportedException("Don't know how to handle concurrency conflicts for " + entry.Metadata.Name); } } // Retry the save operation context.SaveChanges(); } } }