Search code examples
sql-serverentity-frameworkcode-first

How to add a constraint to an EF Code First table


First, I'm not sure if I'm reinventing the wheel with regards to foreign keys here, but lets say I have a Patient table

PatientId
Name
Gender
Age
HospitalId

I want to make sure that when an object is inserted into the Patient table, that it won't insert a record with a HospitalId that doesn't exist in the Hospital table. Is there an efficient way of doing this? Or as I said above am I reinventing a wheel here?


Solution

  • Try this:

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

    Also you can change Hospital class this way:

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