如何首先向 EF 代码添加约束 table

How to add a constraint to an EF Code First table

首先,我不确定我是否在这里重新发明了关于外键的轮子,但可以说我有一个病人 table

PatientId
Name
Gender
Age
HospitalId

我想确保将对象插入患者 table 时,它不会插入医院 table 中不存在的 HospitalId 记录。有没有一种有效的方法来做到这一点?还是如我上面所说,我在这里重新发明了一个轮子?

试试这个:

public class Patient
{
    public int PatientId {get;set;}
    public string Name {get;set;}
    public string Gender {get;set;}
    public int Age {get;set;}
    public int HospitalId {get;set;}

    //add this line of code
    public virtual Hospital Hospital {get;set;}
}

你也可以这样改变Hospitalclass:

public class Hospital 
{
    //your code....
    //new property
    public virtual ICollection<Patient> Patients {get;set;}    
}