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

问题描述 投票:8回答:3

我有两个模型类,一个是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'的类型不匹配。

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

c# asp.net asp.net-mvc entity-framework
3个回答
9
投票

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。你可以找到帮助here


2
投票

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

什么是DoctorID?在哪里定义?

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

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

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

将DoctorId添加到Doctor表中以及与Doctor相关的特定详细信息。专业。

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
}

1
投票

更复杂的错误:

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

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

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

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

原文:enter image description here

在关键领域之后:enter image description here

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

这解决了所有头痛问题。

© www.soinside.com 2019 - 2024. All rights reserved.