父母与子女之间的关系不起作用

问题描述 投票:1回答:1

我在实体框架6中遇到父子关系的问题,其中父母有一个孩子的列表,而孩子的一个是最喜欢的孩子。执行实体添加时,EF抛出该错误:

错误!无法确定相关操作的有效排序。由于外键约束,模型要求或存储生成的值,可能存在依赖关系。

例:

public class Child
{
    public int ChildID { get; set; }
    public string ChildName { get; set; }

    [ForeignKey("Parent")]    
    public int ParentRefId { get; set; }

    public Parent Parent { get; set; }
}

public class Parent
{
    public int ParentId { get; set; }
    public string ParentName { get; set; }

    public int FavoriteChildId {get;set;}

    [ForeignKey("FavoriteChildId")]
    public Child FavoriteChild {get;set;}

    [ForeignKey("ParentRefId")]
    public ICollection<Child> Children { get; set; }
}

它也不起作用:

 public class Child
    {
        public int ChildID { get; set; }
        public string ChildName { get; set; }

        [ForeignKey("Parent")]    
        public int ParentRefId { get; set; }

        public Parent Parent { get; set; }
    }

    public class Parent
    {
        public int ParentId { get; set; }
        public string ParentName { get; set; }

        [ForeignKey("FavoriteChild ")]
        public int FavoriteChildId {get;set;}           

        public Child FavoriteChild {get;set;}            

        public ICollection<Child> Children { get; set; }
    }
c# entity-framework-6 foreign-keys
1个回答
0
投票

我更喜欢fluent api这样的配置,但你可以尝试InverseProperty annotation

public class Child
{
    public int ChildID { get; set; }
    public string ChildName { get; set; }

    // EF will make FK by convention
    public int ParentId { get; set; }
    public Parent Parent { get; set; }

    public int? FavoriteOfParentId { get; set; }
    public Parent FavoriteOfParent { get; set; }
}

public class Parent
{
    public int ParentId { get; set; }
    public string ParentName { get; set; }

    public int FavoriteChildId {get;set;}           
    [InverseProperty("FavoriteOfParent")]
    public Child FavoriteChild {get;set;}            

    [InverseProperty("Parent")]
    public ICollection<Child> Children { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.