Jacques Bronkhorst
Jacques Bronkhorst

Reputation: 1695

How to get nested JSON Reply with WCF an Entity Framework

I have 2 models, A Order Header and Order Detail.

I want to end up with a JSON reply from the Server that looks like:

--OrderHeader 1
  |
   --OrderDetails 1
--OrderHeader 2
  |
   --Order Detail 2

Would I use entity framework create some sort of sub query wand return this via my WebGet, or would I run separate queries and integrate the format after the results have been obtained?

Here are my Viewmodels:

 public class OpenOrderHeader
{
    public int CustomerID { get; set; }
    public int OrderID { get; set; }
    public int OrderUniqueNumber { get; set; }
    public int NumberOfProductsOnOrder { get; set; }
    public DateTime OrderDateCreated { get; set; }
    public DateTime OrderDateUpdated { get; set; }
    public string OrderLocalOnline { get; set; }
    public int BranchID { get; set; }
    public string PaymentMethod { get; set; }
    public int OrderStatus { get; set; }
    public string OrderCurrency { get; set; }
    public decimal OrderConversionRate { get; set; }
    public decimal SubTotalInclTax { get; set; }
    public decimal SubTotalExclTax { get; set; }
    public decimal DiscountInclTax { get; set; }
    public decimal DiscountExclTax { get; set; }
    public decimal ShippingInclTax { get; set; }
    public decimal ShippingExclTax { get; set; }
    public decimal PaymentFeeInclTax { get; set; }
    public decimal PaymentFeeExclTax { get; set; }

}

public class OpenOrderProducts
{
    public int OrderID { get; set; }
    public string ProductSKUName { get; set; }
    public int ProductSKUID { get; set; }
    public string ProductSKUStockCode { get; set; }
    public DateTime ProductAddedToOrder { get; set; }
    public int QtyOfProductsOnOrder { get; set; }
    public decimal UnitPriceinclTax { get; set; }
    public decimal UnitPriceExclTax { get; set; }
    public decimal UnitDiscountInclTax { get; set; }
    public decimal UnitDiscountExclTax { get; set; }
    public decimal LineItemTotalIncludingTax { get; set; }
    public decimal LineItemExclTax { get; set; }
    public decimal LineItemShippingCost { get; set; }
}

Upvotes: 0

Views: 365

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109117

Just create a navigation property Orderdetails on the OrderHeader entity. Then you can query

var data = db.OrderHeaders.Include(h => h.Orderdetails).ToList();

and serialize data into JSON.

I think that in the classes you show OpenOrderHeader would have a collection of OpenOrderProducts?

public virtual ICollection<OpenOrderProduct> OpenOrderProducts { get; set; }

(As you see, I would change the name of the class in OpenOrderProduct, no plural)

Upvotes: 1

Related Questions