c# - 检测到自引用循环

标签 c# entity-framework azure asp.net-web-api

我已经阅读了很多以前针对此问题的解决方案,但没有一个对我有用。

我在事件和用户对象之间有循环关系:

public class Event : EntityData
{
    [Required]
    [ForeignKey("Creator")]
    public string CreatorId { get; set; }
    public User Creator { get; set; }

    [InverseProperty("ParticipantIn")]
    public virtual ICollection<User> Participants { get; set; }

    [InverseProperty("ManagerIn")]
    public virtual ICollection<User> Managers { get; set; }
}

如您所见,我对此类中的 User 进行了三个引用:事件创建者、管理者列表和参与者列表。

用户类还包含对事件的引用:

public class User: EntityData
{
    [InverseProperty("Participants")]
    public virtual ICollection<Event> ParticipantIn { get; set; }

    [InverseProperty("Managers")]
    public virtual ICollection<Event> ManagerIn { get; set; }
}

现在,问题是,当我尝试序列化一个事件时,就像在我的 createEvent 函数中一样,它告诉我存在一个自引用循环,那是因为当创建事件时,我将其添加到创建者的事件中“ManagerIn”集合。

该行导致 Event->Creator->ManagerIn->Event->Creator->..... LOOP

我尝试了任何方法,我还有一个带有公共(public)虚拟用户创建者的代码版本,以便使其延迟加载..

目前,我的解决方案非常不优雅,在将事件返回给我正在执行的客户端之前:

event.Creator = null;

event.Managers = null;

以避免自引用循环。

解决此类问题的正确方法是什么?

提前致谢, 丽然!

最佳答案

我读到这是一种方法。

MyContextEntities.ContextOptions.ProxyCreationEnabled = false;

否则,我建议序列化到不同的对象并避免序列化你的 poco。

关于c# - 检测到自引用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42810150/

相关文章:

c# - 使用 GetProperties 时如何区分 Navigation Properties 与常规 Navigation Properties?

c# - 具有存储库和工作单元的 ASP.NET 标识

ios - 同一实体的核心数据多个实例 - 共享属性的实体

Azure 存储 blob 列表,包含来自特定点的连续 token

azure - 如何在Azure应用服务中指定分层应用程序设置?

c# - 检查字符串是否包含特定单词 C#

c# - Google Protocol Buffers - 序列化为字节数组

c# - 为什么我的 ASP.NET 操作寻找错误的 View ?

c# - Excel 中的下一个单元格列是什么 - 组合/排列

Azure Active Directory 和 owin 身份验证