Sebastián A
Sebastián A

Reputation: 880

Update a virtual property of a model does not work

I have this model

public class Propiedad
{
    [Key]
    public int Id { get; set; }
    public virtual Entidad Entidad { get; set; }
    public virtual PestanasPorEntidad Pestana { get; set; }
    public virtual GrupoDePropiedades Grupo { get; set; }
    public string Codigo { get; set; }
    public string Nombre { get; set; }
    public string TipoDeDatos { get; set; }
    public bool Requerido { get; set; }
    [Required]
    public int Orden { get; set; }
    public string Columna { get; set; }
}

In the edit view I have a dropdown for Grupo property, if I select another value this does not change in the database and remain the old value

Part of the view (Edit)

<div class="form-group">
    @Html.LabelFor(model => model.Grupo, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(m => m.Grupo.Id, (SelectList)(ViewBag.GrupoList), "Seleccionar", new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Grupo)
    </div>
</div>

This is the Edit method

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,Codigo,Nombre,TipoDeDatos,Requerido,Columna,Grupo")] Propiedad propiedad)
    {
        if (ModelState.IsValid)
        {
            var grupo = unitOfWork.GrupoDePropiedadesRepository.GetById(propiedad.Grupo.Id);
            propiedad.Grupo = grupo;
            unitOfWork.PropiedadRepository.Update(propiedad);
            unitOfWork.Save();
            return RedirectToAction("Index", new { entidadId = Request["entidadId"] });
        }
        return View(propiedad);
    }

An this is the update of the GenericRepository

    public void Update(TEntity entityToUpdate)
    {
        _dbSet.Attach(entityToUpdate);
        _context.Entry(entityToUpdate).State = EntityState.Modified;
    }

What I'm doing wrong?

Upvotes: 3

Views: 1046

Answers (1)

ramil89
ramil89

Reputation: 851

I suggest you to retrieve from database whole entity Grupo in Edit action.

Then try to do something like this:

var groupoEntity = unitOfWork.GrupoDePropiedadesRepository.GetById(propiedad.Grupo.Id);

Next you can transfer updates from groupo to groupoEntity. For example:

groupoEntity.PropA = grupo.PropA;
groupoEntity.SomeId = grupo.SomeId;
unitOfWork.GrupoDePropiedadesRepository.Update(groupoEntity);
unitOfWork.Save();

Upvotes: 1

Related Questions