代码优先实体框架映射问题

时间:2018-12-05 10:17:30

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

对于EF6中的代码优先方法,我有以下课程。

这是大师班:

 public class Users
 {
        [NotMapped]
        public string Password { get; set; }
        [Key, Column(Order = 1)]
        public Guid UserId { get; set; }
        [Key, Column(Order = 2)]
        public int ITS { get; set; }
 }

这是子班:

public class Class : CommonFields
    {
        [Key]
        public int ClassId { get; set; }
        public int TeacherITS { get; set; }
        public int CoordinatorITS { get; set; }

        [ForeignKey("TeacherITS, CoordinatorITS"), Column(Order = 2)]
        public virtual Users Users { get; set; }
    }

现在尝试更新数据库时

The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'TeacherITS' on entity 'Class' does not match the type of property 'UserId' on entity 'Users' in the referential constraint 'Class_Users'

我在以下子类中进行了更新:

public class Class : CommonFields
{
    [Key]
    public int ClassId { get; set; }
    [ForeignKey("Teacher"), Column(Order = 2)]
    public int TeacherITS { get; set; }
    [ForeignKey("Coordinator"), Column(Order = 2)]
    public int CoordinatorITS { get; set; }

    public virtual Users Teacher { get; set; }
    public virtual Users Coordinator { get; set; }
}

现在我遇到以下错误:

The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical

1 个答案:

答案 0 :(得分:0)

我不确定您的逻辑,这两个类必须互相引用,这就是为什么缺少属性。应该是这样的:

编辑:

public class Users
 {
     [Key, Column(Order = 1)]
     public Guid UserId { get; set; }

     [Key, Column(Order = 2)]
     public int ITS { get; set; }

     [NotMapped]
     public string Password { get; set; }

     // Reference to Class.

     [ForeignKey("TeacherITS", "CoordinatorITS")]
     public ICollection<Class> Class { get; set; }
}


public class Class : CommonFields
{
    [Key, Column(Order = 1)]
    public int ClassId { get; set; }


    [Column(Order = 2)]
    public int TeacherITS { get; set; }

    [Column(Order = 3)]
    public int CoordinatorITS { get; set; }

    public Users Users { get; set; }
}