Answer the question
In order to leave comments, you need to log in
What is the correct way to update an object in ASP .NET and EF?
The essence of the task is to update the fields of one entity (not tied to EF) that are present in the EF model without affecting other fields.
Now there are several crutch solutions that I really don’t like.
[Authorize]
[HttpPatch]
// PATCH: UserProfile
public ActionResult Index(SimpleUserCard ucard)
{
var uid = User.Identity.Name;
try
{
var user = db.Users.Where(u => u.PhoneNumber == uid).FirstOrDefault();
// вот здесь надо произвести проверку на наличие
//соответствующего поля в принятой модели, и обновлять только
// поля, которые имеются в ней.
user.FirstName = ucard.FirstName;
user.SecondName = ucard.SecondName;
user.Patronymic = ucard.Patronymic;
user.DateBirth = ucard.DateBirth;
user.AvatarId = ucard.AvatarId;
db.SaveChanges();
var up = new UserProfile(user, true);
return Json(new { Status = "Success",UserProfile = up });
} catch
{
return Json(new { Status = "Error" });
}
public IHttpActionResult Patch(int key, UserSpecialisations specialisation)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var userId = AppUser.Id;
//только сам пользователь может обновлять специализации
//проверка на добавление исключительно системных базовый тем специализаций
if (db.UsersSpecialisations.Where(z => z.UserId == userId && z.Specialisation.IsDeleted == false && z.Id == specialisation.SpecialisationId).Any())
{
specialisation.Id = key;
specialisation.UserId = userId;
//для обновления данных должны быть предоставлены все поля (кроме id),
//иначе, те поля которые не указаны станут пустыми
db.UsersSpecialisations.Attach(specialisation);
var entry = db.Entry(specialisation);
entry.State = EntityState.Modified;
entry.Property(e => e.DateAdd).IsModified = false;
entry.Property(e => e.IsDeleted).IsModified = false;
db.SaveChanges();
return Ok();
}
else
{
return BadRequest(ModelState);
}
}
Answer the question
In order to leave comments, you need to log in
For these purposes, you can use automapper. https://github.com/AutoMapper/AutoMapper
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question