【发布时间】:2017-08-11 11:13:37
【问题描述】:
我有两个表,它们通过 OneToMany 关系链接在一起。 Table1 有一个指向 Table2 主键的外键。
当我使用 LINQtoSQL 获取 Table1 中的 a 行时,它会自动获取 Table2 的数据。Table2 引用了 Table1 中的行,它也尝试获取这些行。然后我们开始了一个无限循环
Guid productIdGuid = Guid.Parse(productId);
var info = (from row in db.Info
where row.ProductId == productIdGuid &&
row.ComputerId == null &&
row.DeletedAt == null
select row).FirstOrDefault();
return license;
当我将信息转换为 JSON 时出现 stackoverflow 错误,如下所示:
JsonConvert.SerializeObject(info);
但是我可以通过这个解决:
JsonConvert.SerializeObject(input, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
但是这里的结果看起来不太好
{
"$id":"1",
"ProductId":"a8a78902-777c-4be9-a240-a5e47af6f144",
"ComputerId":null,
"Table2":{
"$id":"2",
"Id":"a8a78902-777c-4be9-a240-a5e47af6f144",
"Reference":"10456975",
"Table1":[
{
"$id":"3",
"ProductId":"a8a78902-777c-4be9-a240-a5e47af6f144",
"ComputerId":"63e57ee7-14d3-e611-80dc-0050569ea396",
"Table2":{
"$ref":"2"
}
},
{
"$ref":"1"
},
.....
]
}
}
我不希望它继续在表格之间获取子项/链接。我只想要一个链接,所以结果看起来像这样:
{
"$id":"1",
"ProductId":"a8a78902-777c-4be9-a240-a5e47af6f144",
"ComputerId":null,
"Table2":{
"$id":"2",
"Id":"a8a78902-777c-4be9-a240-a5e47af6f144",
"Reference":"10456975",
}
}
有什么想法吗?
【问题讨论】:
标签: json linq-to-sql