无法确定从属操作的有效顺序

本文关键字:有效 顺序 操作 无法确定 | 更新日期: 2023-09-27 18:10:16

我想创建一个文件夹对象,其中有文件和其他文件夹,它本身也可能是另一个文件夹的一部分。以下是我的文件:

public class Folder
{
    public Guid Id {get;set;}
    public string Title { get; set; }
    public virtual FolderSettings FolderSettings { get; set; }
    private ICollection<FolderSettings> _folders { get; set; }
    public ICollection<FolderSettings> Folders
    {
        get { return _folders ?? (_folders = new HashSet<FolderSettings>()); }
        set { _folders = value; }
    }
    private ICollection<Files> _files{ get; set; }
    public ICollection<File> Files
    {
        get { return _files?? (_files = new HashSet<File>()); }
        set { _files= value; }
    }
}
public class FolderSettings
{
    [Key, ForeignKey("MyFoder")]
    public Guid FolderId{ get; set; }
    public virtual Folder MyFoder{ get; set; }
    [ForeignKey("RootFolder")]
    public Guid? RootFolderId { get; set; }
    public virtual Folder RootFolder { get; set; }        
}

文件夹设置对象可能有更多的属性,我只是简化了它。得到的错误是:

无法确定相关操作的有效顺序。依赖关系可能由于外键约束、模型需求或存储生成的值而存在。

无法确定从属操作的有效顺序

编辑:

EF没有发现

public virtual FolderSettings FolderSettings { get; set; }

是外键MyFoder的逆。在它上面添加这一行,你的模型就会被理解了:

[InverseProperty("MyFoder")]

在文件夹设置中添加属性

public Folder Folder { get; set; }

并纠正拼写ForeignKey('Foder')。EF将开始工作。

请注意,在文件夹类中,文件夹属性的类型是ICollection<FolderSettings>,但从你的解释来看,ICollection<Folder>是你真正的意思

代码如下:

public class Folder
{
    public Guid Id { get; set; }
    public string Title { get; set; }
    [InverseProperty("MyFoder")]
    public virtual FolderSettings FolderSettings { get; set; }
    private ICollection<FolderSettings> _folders { get; set; }
    public ICollection<FolderSettings> Folders
    {
        get { return _folders ?? (_folders = new HashSet<FolderSettings>()); }
        set { _folders = value; }
    }
    private ICollection<File> _files { get; set; }
    public ICollection<File> Files
    {
        get { return _files ?? (_files = new HashSet<File>()); }
        set { _files = value; }
    }
}
public class File
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}
public class FolderSettings
{
    [Key, ForeignKey("Folder")]
    public Guid FolderId { get; set; }
    public Folder Folder { get; set; }
    public virtual MVAppGroup AppGroup { get; set; }
    [ForeignKey("Group")]
    public Guid? GroupId { get; set; }
    public virtual MVAppGroup Group { get; set; }
}
public class MVAppGroup
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}
public class A : DbContext
{
    public DbSet<Folder> Folders { get; set; }
    public DbSet<File> Files { get; set; }
    public DbSet<FolderSettings> FolderSettings { get; set; }
    public DbSet<MVAppGroup> MVAppGroups { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        using (var a = new A())
        {
            a.Folders.ToList();
        }
    }
}