无法确定关联的主要结尾 - EF Code First

时间:2017-06-21 11:24:44

标签: c# entity-framework ef-code-first

我有一个班级"用户"我添加了以下字段:

    [Required]
    public int CreatedBy_Id { get; set; }

    [ForeignKey("CreatedBy_Id")]
    public User CreatedBy { get; set; }

    public int? UpdatedBy_Id { get; set; }

    [ForeignKey("UpdatedBy_Id")]
    public User UpdatedBy { get; set; } 

当我尝试使用此命令将这些字段推入数据库时​​:

Add-Migration -Configuration DataModel.DevMigrations.Configuration TestAlterUser

我收到此错误:

  

无法确定之间关联的主要结束   类型' DataModel.Entities.User'和   ' DataModel.Entities.User&#39 ;.

     

必须明确配置此关联的主要结尾   使用关系流畅的API或数据注释。

如果我删除了UpdatedBy属性(或CreatedBy),它可以完美地运行。

完整用户的课程:

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [MaxLength(50)]
    public string Login { get; set; }

    [Required]
    [MaxLength(50)]
    public string LastName { get; set; }

    [MaxLength(50)]
    public string FirstName { get; set; }

    [Required]
    public int CreatedBy_Id { get; set; }

    [ForeignKey("CreatedBy_Id")]
    public User CreatedBy { get; set; }

    public int? UpdatedBy_Id { get; set; }

    [ForeignKey("UpdatedBy_Id")]
    public User UpdatedBy { get; set; } 
}

1 个答案:

答案 0 :(得分:1)

尝试使用InverseProperty属性:

public class User
{
    public int Id { get; set; }
    [Required]
    [MaxLength(50)]
    public string Login { get; set; }
    [Required]
    [MaxLength(50)]
    public string LastName { get; set; }
    [MaxLength(50)]
    public string FirstName { get; set; }

    [Required]
    public int CreatedBy_Id { get; set; }
    [ForeignKey("CreatedBy_Id")]
    public virtual User CreatedBy { get; set; }

    public int? UpdatedBy_Id { get; set; }
    [ForeignKey("UpdatedBy_Id")]
    public virtual User UpdatedBy { get; set; } 

    //add these properties
    [InverseProperty("CreatedBy")]
    public virtual ICollection<User> WereCreated {get; set;}
    [InverseProperty("UpdatedBy")]
    public virtual ICollection<User> WereUpdated {get; set;}
}