asp.net mvc 3 and EF , Circular Reference Issue

This problem is caused by the default JSON serializer is not smart enough to deal with Entity of EF reference each other.

there are couple of solving you can find on internet using Automapper, other better json serializer, but In my Opinion the best one is simply, Generate your ViewModel with what property you need.

although I enable all Lazyload that I disabled, am using codefirst. so put back again virtual the issue remain.

In your View page. avoid using Model.Entity.ReferenceEntity.ColumnName, instead generate what you want .

Example :

Order and OrderItems.

avoid using OrderItems.Product.Description

instead in your ViewModel generate ProductDescription.

and on your linq to Entity query

 

   1: var results = (from a in db.tblCmOrderItems.Include("tblCmProduct")
   2:                                  where a.orderID == order.orderID
   3:                                  select new ShoppingCartItem
   4:                                  {
   5:                                      ValidUntil = validUntil,
   6:                                      UnitPrice = a.unitPrice,
   7:                                      UnitCost = a.unitCost,
   8:                                      Quantity = a.quantity,
   9:                                      OrderItemID = a.orderItemID,
  10:                                      ProductName = a.tblCmProduct.productName,
  11:                                      ProductDescription = a.tblCmProduct.description,
  12:                                      ProductID = a.tblCmProduct.productID
  13:                                  }).ToList();

 

This way You keep the rule of Thumb View only deal with what being passed on and follow the ViewModel Concept.

Share this post: | | | |
Published Saturday, February 18, 2012 8:09 PM by cipto

Comments

No Comments