Note that there are some explanatory texts on larger screens.

plurals
  1. POEF 4.1 POCO Accessing navigation properties after Db.Entry()
    primarykey
    data
    text
    <h1>The Problem</h1> <p>Not sure what the right way to do this is... I have a simple class:</p> <pre><code>public partial class Event { public int Id { get; set; } public string Description { get; set; } public int? PreviousEventId { get; set; } public virtual Event PreviousEvent { get; set; } } </code></pre> <p>In my MVC 3 project, I have a form that is used to edit event description and (optionally) select a previous event from a drop down list. Form is submitted to an action and, as usual with MVC 3, automagically mapped to an <code>Event</code>:</p> <pre><code>[HttpPost] public ActionResult SaveEvent(Event myEvent) { if (ModelState.IsValid) { Db.Entry(myEvent).State = EntityState.Modified; // do some additional checks Db.SaveChanges(); } } </code></pre> <p>I'd like to do some additional validation that needs access to <code>PreviousEvent</code> before I save my entity. However, the navigation property is always <code>null</code> when I access it in the code above. This makes sense - the form is mapped directly to my POCO class, <code>Event</code>, and not to its proxy created by EF.</p> <h1>The Question</h1> <p>Is there any way to swap my modified <code>Event</code> for its proxy so that EF can help out with loading its navigation properties? I could do:</p> <pre><code>Db.Entry(myEvent).Reference(e =&gt; e.PreviousEvent).Load(); // do some checking on myEvent.PreviousEvent </code></pre> <p>...but loading all navigation properties this way seems mundane (there's a lot more to this class than shown), and I'm hoping EF has a better way of doing this. Does it indeed?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload