简体   繁体   中英

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?

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;
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM