2015-01-20 207 views
0

我有一個數據庫與兩個表。 客戶訂單。在客戶中引用主鍵Id的訂單中指定的外鍵名爲Customer_Id實體框架實體json

我使用實體框架進行映射。

我想在JavaScriptSerializer以這樣的輸出JSON格式:

[{ 
    "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" } 
       ] 
}] 

是否有一個簡單的方法來實現這一目標?我花了一些時間來找出如何做到這一點,但我似乎得到了「cirkular參考」的問題..

+1

http://stackoverflow.com/questions/657939/serialize-entity-framework-objects-into-json – 2015-01-20 23:20:50

+0

或者使用JSON.NET,我相信對潛在的循環引用有點聰明。 – 2015-01-20 23:58:02

回答

0

使用Newtonsoft.Json,這對LINQ查詢直接支持:

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

有也內置到.NET中的JSON支持,但是這種NuGet包更適合。