How to retrieve an entity with related entities in .net core with raw SQL queries?

asp.net-core c# entity-framework-core linq sql

Question

I have the following models, Visit.cs and Prescription.cs. I want to get all rows of visit with each instance containing the related prescriptions. I use the following EF Core query but the medicines field is always empty. I'm using postgresql as the database. What should I do?

Visit.cs:

public class Visit
{
    public int patient_id { get; set; }
    public DateTime visit_date { get; set; }
    public int doctor_id { get; set; }
    public int prescription_id { get; set; }

    public ICollection<Prescription> prescriptions { get; set; }
}

Prescription.cs:

public class Prescription
{
    public int prescription_id { get; set; }
    public string medicine { get; set; }
    public Visit Visit { get; set; }
}

and my query:

var visits = dbContext.Visits
                      .FromSqlRaw("select * from visit natural join prescription")
                      .ToList();
1
0
1/30/2020 7:58:04 PM

Accepted Answer

The documentation for .FromSqlRaw mentions this in the limitations section

They do give an example of how to include related data however by composing over the raw query:

var visits = dbContext.Visits
  .FromSqlRaw("select * from visit")
  .Include(v=>v.prescriptions)
  .ToList();

I would also strongly recommend that you do NOT use * in any query. List the columns that you need returned. Using * will cause the database to return all the columns, even ones that you don't want. Forcing the database to return the unused columns can cause it to not use indexes it might otherwise be able to use, or cause the database to do row seeks that it really shouldn't need to do. A good example would be a DBA adding columns for things like CreateDate, UpdateDate, CreateUser, UpdateUser and/or RowVersion to help with change tracking or replication.

2
1/30/2020 8:24:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow