Athul Athul - 1 month ago 7
ASP.NET (C#) Question

Map same Model class for multiple purposes in Entity FrameWork

I have two model classes one is

ApplicationUser
and the second is
Appointment
. Application user includes all users that use the application, in my case, Doctors and Data entry operators. Doctors will be assigned to each appointment and Data entry operators will be making this log to DB. I want to map both these users with appointment. I have tried something like this

public class Appointment
{
public int AppointmentID { get; set; }
public DateTime Date { get; set; }

public int DoctorID { get; set; }
[ForeignKey("DoctorID")]
public virtual ApplicationUser Doctor { get; set; }

public int SystemUserID { get; set; }
public virtual ApplicationUser SystemUser { get; set; }
}

public class ApplicationUser : IdentityUser
{
public string Email { get; set; }
public string Mobile { get; set; }
public string FirstNsme { get; set; }
public string LastName { get; set; }
}


But this throws an error


Appointment_Doctor_Target_Appointment_Doctor_Source: : 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 'DoctorID' on entity 'Appointment' does not match the type of property 'Id' on entity 'ApplicationUser' in the referential constraint 'Appointment_Doctor'.


Can anyone point out why this error is occurring and what is the correct approach to this problem?

tmg tmg
Answer

IdentityUser as all entities in asp.net identity entity framework have string as key. You are trying to map to an int. So either use Guids as foreign keys in your Appointment entity

public class Appointment
{
    [Key]
    public int AppointmentID { get; set; }
    public DateTime Date { get; set; }

    public string DoctorID { get; set; }
    [ForeignKey("DoctorID")]
    public virtual ApplicationUser Doctor { get; set; }

    public string SystemUserID { get; set; }
    [ForeignKey("SystemUserID ")]
    public virtual ApplicationUser SystemUser { get; set; }
}

or change the type of Ids in identity classes to int. You can find help here.