webworm
webworm

Reputation: 11019

Populating relationships between POCO classes in EF

I am trying to setup seeding for a project that pulls data from an existing data. The part that is giving me trouble is how to setup the relationships between the tables as I import the data.

I have three tables:
1) Patient
2) InsuranceProvider
3) Doctors

Basically, the Patient has an Insurance Provider, and the Insurance Providers each have several Doctors the patient can choose from. I have setup the following entities.

public class Patient
{
  public int Id {get; set;}
  public string Name {get; set;}
  public int LegacyInsuranceProviderId {get; set;}
  public int InsuranceProviderId {get; set;}
  public virtual InsuranceProvider insuranceProvider {get; set;}
}

public class InsuranceProvider
{
  public int Id {get; set;}
  public int LegacyId {get; set;}
  public string CompanyName {get; set;}
  public virtual ICollection<Patient> patients {get; set;}
  public virtual ICollection<Doctor> doctors {get; set;}
}

public class Doctor
{
  public int Id {get; set;}
  public string DoctorFullName {get; set;}
  public int LegacyInsuranceProviderIdId {get; set;}
  public int InsuranceProviderId {get; set;}
  public virtual InsuranceProvider insuranceProvider {get; set;}
}

The classes all have a field called "Legacy..." this represents the previous primary keys of the respective tables. I am doing this so I don't lose track of the relationships since new primary keys will be generated for each table.

What I cannot figure out is how to populate the relationships between these classes.

Upvotes: 1

Views: 120

Answers (1)

Travis J
Travis J

Reputation: 82267

The setup you have looks good to me.

The virtual keyword used notifies entity framework that that field is a "navigation property". It can use this information to load the data when querying by constructing a join between the two. All you have to do is access the join and it will populate the data. There are two ways.

Let's just assume we are inside of a using block (or injected class) which has db as an already instantiated object of your DbContext.

The first way would be through lazy loading. The doctorPatients variable here is going to now hold a list of that doctor's patients. Note: if the db has been disposed, lazy loading will cause an exception to be thrown.

var doctor = db.Set<Doctor>().Find(1);//get a Doctor by primary key
var doctorPatients = doctor.insuranceProvider.patients;

The second way would be through eager loading. This uses the Include method which instructs the query to join when fetching data and will as a result return the relevant information.

var doctorWithPatients = db.Set<Doctor>.Include(d => d.insuranceProvider.patients).Find(1);

Upvotes: 1

Related Questions