Unable to determine the principle end of the relationship - multiple added entities may have the same primary key

岁酱吖の 提交于 2019-12-16 18:06:58

问题


Sets have Cards and Sets. Here's what I have in my model, using EF Code First:

public class Set
{
    // Primitive Properties 
    [Required]
    [Key]
    public virtual int SetId { get; set; }

    // Navigation Properties 
    [Required]
    public virtual List<Set> Sets { get; set; }

    // Navigation Properties
    [ForeignKey("ParentSet")]
    public int ParentSetId { get; set; }
    public virtual Set ParentSet { get; set; }
}

Then for Cards:

public class Card
{
    // Primitive Properties
    [Required]
    [Key]
    public virtual int CardId { get; set; }

    // Navigation Properties
    [Required]
    [ForeignKey("ParentSet")]
    public int ParentSetId { get; set; }
    public virtual Set ParentSet { get; set; }
}

I'm trying to rebuild the database using 'update-database' from the package manager console and this is the error I'm getting:

Unable to determine the principal end of the 'App.Core.Set_ParentSet' relationship. Multiple added entities may have the same primary key.

Any idea why?


回答1:


To me having this in the Set entity doesn't make sense. It can't refer to itself and be required

// Navigation Properties 
[Required]
public virtual List<Set> Sets { get; set; }

If a Set HAS to have a list of Sets, how can you create the first Set?

Note that from what's written in the error, it has nothing to do with the Card class




回答2:


If you're just trying to avoid the null errors from having a newly instantiated Set with no Sets, then the proper way to handle this is to instantiate Sets in the constructor:

public class Set
{
    public Set()
    {
        Sets = new List<Set>();
    }

    ...
}


来源:https://stackoverflow.com/questions/15164028/unable-to-determine-the-principle-end-of-the-relationship-multiple-added-entit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!