【问题标题】:EF Code First Cyclical ReferenceEF Code First 循环参考
【发布时间】:2012-05-04 01:50:08
【问题描述】:

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

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。

有什么想法吗?

【问题讨论】:

  • FileInformations 是否以任何方式参与其中?我没有得到您显示的代码的周期性参考。
  • 除此之外你还有其他流畅的配置吗?
  • 你找到答案了吗?我面临着类似的情况。
  • 我最终通过使用代码优先的“逆向工程”工具解决了这个问题。 visualstudiogallery.msdn.microsoft.com/…

标签: entity-framework ef-code-first


【解决方案1】:

您好,更改 Id 而不是使用 [key] 修改的 FolderId、IconId。因为你不使用映射流利的代码,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; }
}

【讨论】:

    猜你喜欢
    • 2019-02-13
    • 2013-05-21
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    相关资源
    最近更新 更多