【问题标题】:LINQtoSQL - Keeps self referencingLINQ to SQL - 保持自引用
【发布时间】: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


    【解决方案1】:

    您可以在 Table2 类中将 [JsonIgnore] 属性添加到您想要忽略的所有属性中,在您的情况下这将是 Table1 引用

    public class Table2
    {
        ...
    
        [JsonIgnore] 
        public ICollection<Table1> Table1 { get; set; }
    
        ...
    }
    

    【讨论】:

    • 如果我输入这个,不幸的是没有任何改变。我仍然得到儿童参考
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多