What is independent association actually doing here? What is its purpose? RRS feed

  • Question

  • User1790019738 posted

    Hi guys, 

    I have been desperately trying to get my head around independent and FK associations. 

    I have 2 models connected up with EF (I've left out few non-relevant properties): 

    public class Item
        public int Id { get; set; }
        public string Name { get; set; }        
        public Categories Category { get; set; }
    [Required] public int BoxId { get; set; } public virtual Box Box { get; set; } }

    public class Box
    public int Id { get; set; }
    public string Label { get; set; }
    public virtual ICollection<Item> Items { get; set; }

    A box contains many items and so it's a 1..* relationship. When I create an item, I want a dropdown list to appear with all the available boxes. 

    I have actually achieved this, but I am now trying to analyse and understand what EF is actually doing. 

    For reference, here is my controller code:

    public ActionResult Create()
    ViewBag.BoxesId = new SelectList(_db.Boxes, "Id", "Label");
    return View();

    [HttpPost] public ActionResult Create(Item item) { if (ModelState.IsValid) { _db.Items.Add(item); _db.SaveChanges(); return RedirectToAction("Details", new { id = item.Id }); } ViewBag.BoxesId = new SelectList(_db.Boxes, "Id", "Label"); return View(item); }

    And here is the dropdown menu:

    <div class="form-group">
        @Html.LabelFor(model => model.BoxId, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">               
            @Html.DropDownListFor(model => model.BoxId, ViewBag.BoxesId as SelectList, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.BoxId, "", new { @class = "text-danger" })

    Now on submitting the form, my item property contains all the details I would expect, such as the box id, item.name etc. however, the actual Box box reference is null, which makes me wonder why is this even necessary? If I have the item and I want to find out the box, I can simply do a quick FK lookup and retrieve the box object. So why do I need the Box box independent association? 

    I'm sure I am missing something and would be delighted if someone could hopefully explain to me the item's "Box box" reference purpose. Smile

    I took a further stab in understanding this and I guess I could add something like below in the controller POST method, which would populate the box reference, but I doubt this is its intended purpose!

     item.Box = _db.Boxes.Find(item.BoxId); 

    Thanks in advance! 

    Wednesday, January 18, 2017 8:24 PM