EF代码优先循环引用问题

3

我有一系列代表文件夹和文件的对象。文件夹当然可以有一组文件,但它们也可以有子文件夹。文件夹有一个指向父文件夹的引用,这可能是问题的起源。此外,文件夹可以有与之关联的图标。

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 ]*
我不确定这里是什么循环引用。Folder只有一次引用Icon,而Icon根本没有引用folder。
一个问题是,我不确定如何正确地将ParentFolderId映射回父文件夹的FolderId。
有任何想法吗?

文件信息是否有任何参与?我在您展示的代码中并没有看到循环引用。 - Gert Arnold
除此之外,你是否正在进行任何流畅的配置? - NSGaga-mostly-inactive
你找到答案了吗?我也遇到了类似的情况。 - Shimmy Weitzhandler
我最终通过使用“反向工程”代码生成工具来解决这个问题。http://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d - Todd Davis
1个回答

0

你好,使用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; }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接