【发布时间】:2023-04-01 11:04:02
【问题描述】:
我有一个来自 EF 实体的以下模型:
public partial class Commodity
{
public Commodity()
{
this.CommodityVarieties = new HashSet<CommodityVariety>();
}
public int CommodityID { get; set; }
public string CommodityName { get; set; }
public string CommodityVarietyDisplayName { get; set; }
public string BackColor { get; set; }
public string ForeColor { get; set; }
public bool IsDeleted { get; set; }
public int SortOrder { get; set; }
public virtual ICollection<CommodityVariety> CommodityVarieties { get; set; }
}
public partial class CommodityVariety
{
public int VarietyID { get; set; }
public int CommodityID { get; set; }
public string VarietyName { get; set; }
public bool IsDeleted { get; set; }
public virtual Commodity Commodity { get; set; }
}
我想获取商品列表并使用Newtonsoft 将该列表转换为 JSON 字符串。因此,我写了
DbContext context = new DbContext();
var list = context.Commodities.ToList();
string json = JsonConvert.SerializeObject(list);
我遇到以下错误:
检测到具有类型的属性“商品”的自引用循环 'System.Data.Entity.DynamicProxies.Commodity_B55D25F995ED72E0B75FED715153713965D91EB5A3BF576322FE6DEAC130C0F5'。 路径'[0].CommodityVariety[0]
我知道这是因为 CommodityVariety 类中对 Commodity 的引用。
为避免我将 JSON 序列化设置更新为将 ReferenceLoopHandling 改为 Ignore,如下所示:
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
以上设置给我
引发了“System.OutOfMemoryException”类型的异常。
我已经尝试了 StackOverflow 中所有可能的答案。
我终于做到了
public DbContext() : base("name=DbContextEntity")
{
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
}
现在,我运行代码没有任何错误,Commodity.CommodityVarieties 为空。
我有这么多外键,在将ProxyCreationEnabled 设置为false 后,很难手动映射它们。
有没有办法在 JSON 序列化之前识别自引用并使其为空?如下:
DbContext context = new DbContext();
var list = context.Commodities.ToList();
//filter only properties of `Commodity` property and find object of type `Commodity`
//var suspectObjects = list.Any(x => x.OfType<Commodity>()).ToList();
//suspectObjects.ForEach(item => { item = null; });
//I know the above segment will not work. I seek your help and I thought something like above explain more to you what I want actually.
string json = JsonConvert.SerializeObject(list);
【问题讨论】: