简体   繁体   中英

Saving child entity is not saving the foreign key with entity framework

I have the following entities:

 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; }
    }

And I have this controller action

 [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);
        }

and on my view:

<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>

However when I debug the controller the Entidad property on the Propiedad entity is NULL

http://screencast.com/t/CSgLzSCw

在Create方法的有关DataAnnotation Bind的声明中,您不包括Entidad属性,永远不会被绑定,只需删除Bind DataAnnotation或包括它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM