E
E
Egor Mikheev2017-09-11 17:47:43
ASP.NET
Egor Mikheev, 2017-09-11 17:47:43

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" });
        }

There is another solution, but it is also not very satisfactory.
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

2 answer(s)
M
Michael, 2017-09-12
@dmitrievMV

For these purposes, you can use automapper. https://github.com/AutoMapper/AutoMapper

E
eRKa, 2017-09-14
@kttotto

Here is a similar question

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question