简体   繁体   English

如何使用原始 SQL 查询在 .net core 中检索具有相关实体的实体?

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

I have the following models, Visit.cs and Prescription.cs .我有以下模型, Visit.csPrescription.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.我使用以下 EF Core 查询,但medicines字段始终为空。 I'm using postgresql as the database.我使用 postgresql 作为数据库。 What should I do?我该怎么办?

Visit.cs:访问.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:处方.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();

The documentation for .FromSqlRaw mentions this in the limitations section .FromSqlRaw文档限制部分提到了这一点

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.一个很好的例子是 DBA 为 CreateDate、UpdateDate、CreateUser、UpdateUser 和/或 RowVersion 之类的内容添加列,以帮助进行更改跟踪或复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM