entity-framework - EF代码优先循环引用

标签 entity-framework ef-code-first

我有一系列代表文件夹和文件的对象。文件夹当然可以有文件的集合,但它们也可以有子文件夹。文件夹具有对父文件夹的引用。这可能是麻烦开始的地方。文件夹也可以有与之关联的图标。

public class Folder
{
    [Key]
    public int FolderId { get; set; }
    public string FolderName { get; set; }
    public int ParentFolderId { get; set; }
    public virtual Folder ParentFolder { get; set; }
    public int IconId { get; set; }
    public virtual Icon Icon { get; set; }

    public virtual ICollection<FileInformation> FileInformations { get; set; }
    public virtual ICollection<Folder> Folders { get; set; }
}

public class Icon
{
    [Key]
    public int IconId { get; set; }
    public string IconUrl { get; set; }
    public string Description { get; set; }
}

当我运行该应用程序并尝试获取图标列表时,我收到此错误消息:

*引用关系将导致不允许的循环引用。 [约束名称 = FK_Folder_Icon_IconId]*

我不是 100% 知道这里有循环引用。文件夹只引用一次图标,而图标根本不引用文件夹。

一个问题,这可能是相关的,是我不确定如何使 ParentFolderId 正确映射回父文件夹的 FolderId。

有什么想法吗?

最佳答案

您好,更改 Id 而不是 FolderId、IconId,它们是用 [key] 修改的。因为你没有使用映射流代码,而且 EF 只能假定与名称和类型的关系。

它正在工作。

public class Folder
{
    [Key]
    public int Id { get; set; }

    public string FolderName { get; set; }
    public virtual int ParentId { get; set; } /*ParentFolderId*/
    public virtual Folder Parent { get; set; } /*ParentFolder*/
    public virtual int IconId { get; set; }
    public virtual Icon Icon { get; set; }

    public virtual ICollection<Folder> Children { get; set; } /*not Folders*/

   //it is out of subject 
   //public virtual ICollection<FileInformation> FileInformations { get; // set; }
}

public class Icon
{
    [Key]
    public int Id { get; set; }

    public string IconUrl { get; set; }
    public string Description { get; set; }
}

关于entity-framework - EF代码优先循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10441662/

相关文章:

c# - EF Code First 中自引用实体的映射

entity-framework - 没有事务的 Entity Framework 5

c# - 如何在自动生成的 Edmx 文件中设置 Entity Framework CommandTimeout

entity-framework - 为什么我的外键引用属性没有反射(reflect)外键 ID 属性值?

c# - Ef Code First 外键失败

entity-framework - EF4.1 代码优先 : Stored Procedure with output parameter

nhibernate - 为什么 Entity Framework 不支持 ODBC?

asp.net-mvc - 如何防止在DataFirst First模型中删除DataAnnotations属性

entity-framework - 我应该关闭 Entity Framework 中的延迟加载吗?

ef-code-first - EF迁移: Move Table from 2 Column PK to Single Column causes ALTER before DROP and fails