简体   繁体   中英

Code-First Entity Framework mapping issues

I have a below classes for the Code First Approach in EF6.

This is the master class:

 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; }
 }

This is child class:

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; }
    }

now while trying to update the database i am getting

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'

I made updates in the child class below:

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; }
}

and now i am getting below error:

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

I'm not sure to understand your logic, the 2 class have to reference each other, it's why is missing property. It should be something like this :

Edit :

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM