Navigation Properties on Post Action

423 views Asked by At

I need to access navigation properties on a post edit action but the current way I did that looks not the best alternative as I make a call to database and "reupdate" the model. Is there a better solution?

public class Foo
{
    public int Id { get; set; }
    public string SomeProp { get; set; }
}

public class Bar
{
    public int Id { get; set; }
    public int FooId { get; set; }
    public Foo Foo { get; set; }
}

[HttpPost]
public ActionResult Edit(Bar bar)
{
    // Here bar.FooId is set but bar.Foo is null as bar is not a Dynamic Proxy.

    ...

    bar = db.Bar.Find(bar.id);
    TryUpdateModel(bar);

    return View(bar);  // Here bar.Foo is set.
}

Another way I found is:

db.Bar.Attach(bar);
db.Entity<Bar>(bar).Reference(b => b.Foo).Load();

But it requires I make a reference to all navigation properties I need.

1

There are 1 answers

0
mreyeros On

I am not 100% sure if this is the correct or best way of doing it but, in your UI form that is handling the post either the UI elements need to be bound to the navigation properties or you could also pass them along as hidden fields if they are not being modified

<!-- example of hidden properties -->
@Html.HiddenFor(x=>x.Foo.FooId)

<!-- exampld of editable UI element mapped to navigation property's someprop property -->
@Html.TextBoxFor(x=>x.Foo.SomeProp)