0

I have a Database with two tables. Customers and Orders. There is a foreign key named Customer_Id specified in the Orders referencing the primary key Id in Customers.

I use entity framework for mappings.

I would like to the JavaScriptSerializer in order to output json format like this:

[{ 
    "Id": 1,
    "Name": "Liam",
    "Orders": [
                  { "Id" : 1, "Date": "1232144213" }, 
                  { "Id" : 2, "Date": "1232144213" } 
              ]
},
{ 
    "Id": 2,
    "Name": "Martin",
    "Orders": [
                  { "Id" : 3, "Date": "1232144213" }, 
                  { "Id" : 4, "Date": "1232144213" },
                  { "Id" : 5, "Date": "1232144213" } 
              ]
}]

Is there an easy way to achieve this? I have spend some time figuring out how to do it, but I seem to get a problem with a "cirkular reference"..

Peter
  • 505
  • 5
  • 12

1 Answers1

0

Use Newtonsoft.Json, which has direct support for LINQ queries:

    internal class Entity
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public IEnumerable<Order> Orders { get; set; }

        internal class Order
        {
            public string Id { get; set; }
            public DateTime Date { get; set; }
        }
    }

    static void Main(string[] args)
    {
        var customers = new List<Entity>
        {
            new Entity
            {
                Id = "test1",
                Name = "test2",
                Orders = new[] {new Entity.Order
                                {
                                    Id = "testprop", 
                                    Date = DateTime.UtcNow
                                }}
            }
        };
        var json = JObject.FromObject(new {Customers = customers});
        Console.WriteLine(json);
    }

There's also JSON support built into .NET that does similar, but this NuGet package is preferable.

John Castleman
  • 1,552
  • 11
  • 12