在包含导航属性时如何阻止 Entity Framework 核心创建 "Self Referencing Loops"?
How do I stop Entity Framework Core from creating "Self Referencing Loops" when including navigation properties?
亲爱的程序员朋友们!
我的问题是,当我包含导航 属性,例如:User.Pets,
不仅 Pets 集合包含在实体中,而且每个 Pet 都有一个参考槽,通过它导航 属性 到用户。
(延迟加载已关闭)
这很好,因为我们可以在 Json 序列化器中使用 SelfReferencingLoopHandling.Ignore 选项,但即使在没有那么大的集合中,有很多导航属性,这也会变得非常慢。
造成这种情况的主要原因是序列化程序处理引用的方式。对此也有一个解决方案,称为“PreserveReferencesHandling.Objects”,但它会弄乱结果 JSON 文件。
所以,综上所述,最好找到一个选项,而不是首先创建自引用循环,然后尝试解决它们。
谢谢大家!
这里的问题很难理解,我会说你可以使用标签 [JsonIgnore] 来表示你不想在结果中 return 的属性。
示例:https://www.newtonsoft.com/json/help/html/PropertyJsonIgnore.htm
类型
public class Account
{
public string FullName { get; set; }
public string EmailAddress { get; set; }
[JsonIgnore]
public string PasswordHash { get; set; }
}
用法:
Account account = new Account
{
FullName = "Joe User",
EmailAddress = "joe@example.com",
PasswordHash = "VHdlZXQgJ1F1aWNrc2lsdmVyJyB0byBASmFtZXNOSw=="
};
string json = JsonConvert.SerializeObject(account);
Console.WriteLine(json);
// {"FullName":"Joe User","EmailAddress":"joe@example.com"}
亲爱的程序员朋友们!
我的问题是,当我包含导航 属性,例如:User.Pets, 不仅 Pets 集合包含在实体中,而且每个 Pet 都有一个参考槽,通过它导航 属性 到用户。 (延迟加载已关闭)
这很好,因为我们可以在 Json 序列化器中使用 SelfReferencingLoopHandling.Ignore 选项,但即使在没有那么大的集合中,有很多导航属性,这也会变得非常慢。
造成这种情况的主要原因是序列化程序处理引用的方式。对此也有一个解决方案,称为“PreserveReferencesHandling.Objects”,但它会弄乱结果 JSON 文件。
所以,综上所述,最好找到一个选项,而不是首先创建自引用循环,然后尝试解决它们。
谢谢大家!
这里的问题很难理解,我会说你可以使用标签 [JsonIgnore] 来表示你不想在结果中 return 的属性。
示例:https://www.newtonsoft.com/json/help/html/PropertyJsonIgnore.htm
类型
public class Account
{
public string FullName { get; set; }
public string EmailAddress { get; set; }
[JsonIgnore]
public string PasswordHash { get; set; }
}
用法:
Account account = new Account
{
FullName = "Joe User",
EmailAddress = "joe@example.com",
PasswordHash = "VHdlZXQgJ1F1aWNrc2lsdmVyJyB0byBASmFtZXNOSw=="
};
string json = JsonConvert.SerializeObject(account);
Console.WriteLine(json);
// {"FullName":"Joe User","EmailAddress":"joe@example.com"}