保存子实体不是使用实体框架保存外键
本文关键字:保存 实体 框架 | 更新日期: 2023-09-27 17:55:57
我有以下实体:
public class Entidad
{
[Key]
public int Id { get; set; }
public string Nombre { get; set; }
public virtual ICollection<Propiedad> Propiedades { get; set; }
}
public class Propiedad
{
[Key]
public int Id { get; set; }
public virtual Entidad Entidad { get; set; }
public string Codigo { get; set; }
public string Nombre { get; set; }
public string TipoDeDatos { get; set; }
}
我有这个控制器动作
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="Id,Codigo,Nombre,TipoDeDatos")] Propiedad propiedad)
{
if (ModelState.IsValid)
{
db.Propiedades.Add(propiedad);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(propiedad);
}
在我看来:
<div class="form-group">
@Html.LabelFor(model => model.Entidad, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.Entidad.Id, (SelectList)(ViewBag.EntidadList), "Seleccionar", new { @class = "form-control" })
</div>
</div>
但是,当我调试控制器时,Propiedad 实体上的 Entidad 属性为 NULL
http://screencast.com/t/CSgLzSCw
在 Create 方法的 DataAnnotation Bind 声明中,您不包括 Entidad 属性,永远不会绑定,只需删除 Bind DataAnnotation 或包含它。