【问题标题】:Entity framework entities to json实体框架实体转json
【发布时间】:2015-01-20 23:16:48
【问题描述】:

我有一个包含两个表的数据库。 客户订单。订单中指定了一个名为 Customer_Id 的外键,引用了客户中的主键 Id

我使用实体框架进行映射。

我想使用 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" } 
              ]
}]

有没有简单的方法来实现这一点?我花了一些时间弄清楚如何去做,但我似乎遇到了“循环引用”的问题..

【问题讨论】:

标签: c# linq entity-framework asp.net-mvc-4


【解决方案1】:

使用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 包更可取。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多