繁体   English   中英

在实体框架中为多个目的映射相同的Model类

[英]Map same Model class for multiple purposes in Entity FrameWork

我有两个模型类,一个是ApplicationUser ,第二个是Appointment 应用程序用户包括使用该应用程序的所有用户,在我的案例中,是医生和数据输入操作员。 医生将被分配到每个约会,数据输入操作员将这个日志记录到DB。 我想要预约这些用户。 我尝试过这样的事情

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

但这会引发错误

Appointment_Doctor_Target_Appointment_Doctor_Source ::参照约束的从属角色中的所有属性的类型必须与主体角色中的相应属性类型相同。 实体'Appointment'上的属性'DoctorID'的类型与参照约束'Appointment_Doctor'中实体'ApplicationUser'上的属性'Id'的类型不匹配。

任何人都可以指出为什么会出现此错误以及解决此问题的正确方法是什么?

IdentityUser作为asp.net身份实体框架中的所有实体都具有string作为键。 您正在尝试映射到int 因此,要么在指定实体中使用Guids作为外键

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

或者将标识类中的ID类型更改为int。 你可以在这里找到帮助。

您的课程中存在多个问题。

什么是DoctorID? 在哪里定义?

您需要首先关注逻辑上在您的实体之间建立正确的关系。

我认为您的Appointment类不需要包含添加约会的SystemUserID。

其次,如果您想在两种用户类型之间共享一些属性,而不是创建一个公共类并在Doctor和SystemUser中派生。

将DoctorId添加到Doctor表中,以及有关Doctor例如Specialty的特定详细信息。

SystemUser添加一个约会,因此该表应包含与之相关的数据,即doctorId和appointmentId。

更新:

根据您的评论,您可以做这样的事情。 请注意它仅供参考,您最好定义更好的DB Schema。

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

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

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

public class ApplicationUser
{
    public int ApplicationUserId { get; set; }
    public string Email { get; set; }
    public string Mobile { get; set; }
    public string FirstNsme { get; set; }
    public string LastName { get; set; }
    public UserType UserType { get; set; }
}

public enum UserType
{
    Doctor,
    SystemUser
}

更复杂的错误:

我在4个链接表中多次出现此错误。

每个表具有3-7个字段的复合键,并且一个表引用其自己的3字段键,其具有其自己列的不同混合。

我通过修复一个字段序列(确实修复了其他帖子中提到的错误)已经挣扎了多年,只是为了在其他实体中产生连锁反应。

解决方案: 按照减少发生的顺序对齐所有链接表的FK字段

本来: 在此输入图像描述

关键字段后对齐: 在此输入图像描述

并在DbContext中重新排序FluentAPI中的所有匿名FK对象以匹配新订单。

这解决了所有头痛问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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