1

I have the Users Model follows:

Model Users.cs

    [Key]
    [Column("cod")]
    public int Cod { get; set; }
    [Column("nome")]
    [StringLength(120)]
    public string Nome { get; set; }
    [Column("sobrenome")]
    [StringLength(80)]
    public string Sobrenome { get; set; }
    [Column("email")]
    [StringLength(60)]
    public string Email { get; set; }
    [Column("password")]
    [StringLength(20)]
    public string Password { get; set; }

And I also have the ViewModel only with the data shown in View UsersViewModel.cs

    public int Cod { get; set; }
    public string Nome { get; set; }
    public string Sobrenome { get; set; }

My generic repository looks like this:

    public void Update(TEntity obj)
    {
        Db.Entry(obj).State = EntityState.Modified;
        Db.SaveChanges();
    }

In my controller it looks like this:

    [HttpPost]
    public IActionResult SalvaPerfil([FromBody] UsersViewModel usersViewModel)
    {
        if (ModelState.IsValid)
        {
            var user = Mapper.Map<UsersViewModel, Users>(usersViewModel);
            _PetApp.Update(user);
            return Content("fim...");
        }
        return Content("ERRO");
    }

The problem is that the Email and Password fields are being written as NULL in the database, I do not want to change the Email and Password values as they are changed in another View.

I saw this other post, but it is not with Generic Repository, I could not implement it ..

How to update only one field using Entity Framework?

In this case do I need to create a custom method for this change? or is there any way to only change the fields that are in the ViewModel?

Thanks!

5
  • 1
    Get the entity from database, update properties you need and save changes.
    – Mrg Gek
    Jun 14, 2018 at 20:33
  • @MrgGek How would I do that? a foreach in "TEntify obj"? could you give me a practical example? thank you!
    – MariINova
    Jun 14, 2018 at 20:41
  • 1
    Select the entity from database by its Id. var entity = Db.Set(obj).FirstOrDefault(e => e. Cod == cod); var user = entity as User; user.Name = "Changed"; Update(user);
    – Mrg Gek
    Jun 14, 2018 at 20:46
  • I understand what should be done, the problem is that my Repository is generic "public void Update (TEntity obj)", I do not know which Entity it is working on, I will create a custom method to update only a few fields of the entity while I keep searching. ..
    – MariINova
    Jun 14, 2018 at 21:17
  • I did what you checked me in the Controller, get the current user is updated the required fields .. thanks!
    – MariINova
    Jun 14, 2018 at 21:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy