Tom
Tom

Reputation: 8180

Entity Framework 4.1. Loading navigational properties from Ids

I have a bunch of properties like this on OrderItem:

        public virtual Frame Frame { get; set; }
        [ForeignKey("Frame")]
        public int? FrameId { get; set; }

I have a controller like this:

    public ActionResult CostOptions(OrderItem oi)

I am setting the Ids on oi with model binding as above, now is there a way to get the navigational properties to load automatically from the Ids? Do I need to insert the entity to do this?

Upvotes: 0

Views: 80

Answers (1)

Eranga
Eranga

Reputation: 32447

The OrderItem has to be a proxy created by EF inorder to load the navigational property pointed by the relevant id. Your current implementation does not allow this because MVC model binder creates the instance OrderItem.

public ActionResult CostOptions()
{
     // creates instance of the proxy
     var oi = db.OrderItems.Create();

     if (TryUpdateModel(oi))
     {
          // new entity has to be added before retrieving lazy loaded prop
          db.OrderItems.Add(oi);
          // lazy loaded property
          var frame = oi.Frame;
     }
}

Upvotes: 1

Related Questions