EF 4.1 POCO Accessing navigation properties after Db.Entry()
The Problem
Not sure what the right way to do this is... I have a simple class:
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; }
}
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 Event
:
开发者_如何学Go[HttpPost]
public ActionResult SaveEvent(Event myEvent)
{
if (ModelState.IsValid)
{
Db.Entry(myEvent).State = EntityState.Modified;
// do some additional checks
Db.SaveChanges();
}
}
I'd like to do some additional validation that needs access to PreviousEvent
before I save my entity. However, the navigation property is always null
when I access it in the code above. This makes sense - the form is mapped directly to my POCO class, Event
, and not to its proxy created by EF.
The Question
Is there any way to swap my modified Event
for its proxy so that EF can help out with loading its navigation properties? I could do:
Db.Entry(myEvent).Reference(e => e.PreviousEvent).Load();
// do some checking on myEvent.PreviousEvent
...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?
What you ask for is support for lazy loading on entity instances passed to your actions. Lazy loading is provided via dynamic proxy (= dynamically created derived type) created by EF. Once the instance is created without the proxy it cannot use lazy loading and it cannot be changed to allow it!
To create an instance with support for lazy loading you must use:
Event event = context.Events.Create();
but default model binder uses simply default constructor.
Event event = new Event();
So if you want support for lazy loading you must write your own model binder for that.
Once you have proxied instance you can simply attach instance to the context and lazy loading should work for you.
精彩评论