我有这个模型
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; }
}
在编辑 View 中,我有一个 Grupo 属性的下拉列表,如果我选择另一个值,这不会在数据库中更改并保留旧值
部分 View (编辑)
<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>
这是编辑方法
[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);
}
这是 GenericRepository 的更新
public void Update(TEntity entityToUpdate)
{
_dbSet.Attach(entityToUpdate);
_context.Entry(entityToUpdate).State = EntityState.Modified;
}
我做错了什么?
最佳答案
我建议您在编辑操作中从数据库中检索整个实体 Grupo
。
然后尝试做这样的事情:
var groupoEntity = unitOfWork.GrupoDePropiedadesRepository.GetById(propiedad.Grupo.Id);
接下来,您可以将更新从 groupo
传输到 groupoEntity
。例如:
groupoEntity.PropA = grupo.PropA;
groupoEntity.SomeId = grupo.SomeId;
unitOfWork.GrupoDePropiedadesRepository.Update(groupoEntity);
unitOfWork.Save();
关于c# - 更新模型的虚拟属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31949854/