繁体   English   中英

包含导航属性时,如何阻止 Entity Framework Core 创建“自引用循环”?

[英]How do I stop Entity Framework Core from creating “Self Referencing Loops” when including navigation properties?

亲爱的程序员!

我的问题是,当我包含导航属性时,例如:User.Pets,不仅 Pets 集合包含在实体中,而且每个 Pet 都通过它的导航属性对用户进行引用。 (LazyLoading 已经关闭)

这很好,因为我们可以在 Json 序列化程序中使用 SelfReferenceLoopHandling.Ignore 选项,但即使在没有那么大的 collections 中,由于有很多导航属性,这会变得非常慢。

造成这种情况的主要原因是序列化程序如何处理引用。 还有一个解决方案,它被称为“PreserveReferencesHandling.Objects”,但它弄乱了结果 JSON 文件。

因此,总而言之,最好找到一个选项,而不是首先创建自引用循环,然后尝试解决它们。

谢谢大家!

这里的问题很难理解,我想说您可以将标签 [JsonIgnore] 用于您不想在结果中返回的属性。

示例: 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"}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM