我尝试序列化从实体数据模型.edmx自动生成的POCO类,当我使用
JsonConvert.SerializeObject
我得到了以下错误:
为System.data.entity类型检测到自我引用循环错误。
我怎么解决这个问题?
我尝试序列化从实体数据模型.edmx自动生成的POCO类,当我使用
JsonConvert.SerializeObject
我得到了以下错误:
为System.data.entity类型检测到自我引用循环错误。
我怎么解决这个问题?
当前回答
团队:
这适用于ASP。核心网;上面的挑战是如何“设置为忽略”。根据您设置应用程序的方式,这可能相当具有挑战性。以下是对我有效的方法。
这可以放在你的公共void ConfigureServices(IServiceCollection services)部分。
services.AddMvc().AddJsonOptions(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
其他回答
简单地放置Configuration。ProxyCreationEnabled = false;在上下文文件中;这样问题就解决了。
public demEntities()
: base("name=demEntities")
{
Configuration.ProxyCreationEnabled = false;
}
您也可以将属性应用到属性。 [JsonProperty(ReferenceLoopHandling =…)属性非常适合这一点。
例如:
/// <summary>
/// Represents the exception information of an event
/// </summary>
public class ExceptionInfo
{
// ...code omitted for brevity...
/// <summary>
/// An inner (nested) error.
/// </summary>
[JsonProperty( ReferenceLoopHandling = ReferenceLoopHandling.Ignore, IsReference = true )]
public ExceptionInfo Inner { get; set; }
// ...code omitted for brevity...
}
希望有帮助, 扬
c#代码:
var jsonSerializerSettings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
var jsonString = JsonConvert.SerializeObject(object2Serialize, jsonSerializerSettings);
var filePath = @"E:\json.json";
File.WriteAllText(filePath, jsonString);
最简单的方法是安装Json。网 从nuget中添加[JsonIgnore]属性到类的虚拟属性中,例如:
public string Name { get; set; }
public string Description { get; set; }
public Nullable<int> Project_ID { get; set; }
[JsonIgnore]
public virtual Project Project { get; set; }
尽管这些天,我创建了一个只包含我想要传递的属性的模型,所以它更轻,不包括不需要的集合,并且当我重新构建生成的文件时,我不会丢失我的更改……
我喜欢从Application_Start()做它的解决方案,在这里的答案
显然,我不能在JavaScript中使用我的函数中的配置访问json对象,因为在DalSoft的答案中返回的对象在对象的(键,val)上都有“\n \r”。
不管怎样,只要能工作就好(因为不同的方法在不同的场景下工作,这取决于所提出的意见和问题),尽管最好采用一种标准的方法,并提供一些良好的文档支持该方法。