c# - 更新模型的虚拟属性不起作用

标签 c# asp.net asp.net-mvc entity-framework

我有这个模型

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/

相关文章:

c# - 有关更新行数据不起作用的功能

c# - 将 ASP.NET Identity 用户链接到用户详细信息表

asp.net-mvc - "Sorry, an error occurred while processing your request."消息的直接原因和来源是什么?

c# - 如何在列表框中加载所有已知的颜色?

c# - 如何从 ELMAH 中排除 404

c# - 从 .NET 应用程序将 "Hello World"发布到 Twitter

asp.net - 自定义 asp.net 页面中的 Microsoft Communicator 存在指示器(状态指示器)

c# - 从多个位置创建脚本包

javascript - 无法在 Asp.net 文件上传更改事件调用时保留文本框值?

asp.net-mvc - Telerik MVC 网格未正确分组