如何首先在代码中获取具有外键关系的子实体中的父实体属性?

How to get parent entity property in child entity with foreign key relation in code first?

我有以下两个实体 Doctor(parent) 和 DoctorPayment(child)

  1. 一种可能的方法是在 DoctorPayment 实体中获取 Doctor 对象并通过 Doctor.Name

  2. 但我只需要 DoctorName 而不是 DoctorPayment 中应该由 DoctorId 映射的整个对象

我只提到了 Doctor 实体的几个属性,但它有大约 50 个属性,所以我不想在 DoctorPayment 中使用 Doctor 对象

public class Doctor
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Designation { get; set; }
        public int ModifiedBy { get; set; }
    }

    public class DoctorPayment
    {
        public int Id { get; set; }
        public int DoctorId { get; set; }
        public decimal Amount { get; set; }
        public DateTime Date { get; set; }
        public int ModifiedBy { get; set; }
        public Doctor Doctor { get; set; }      // a possible way to take Doctor object
    }
db.DoctorPayment.Include(x=>x.Doctor).Where(...).Select(x=>new{docName=x.Doctor.Name,.....})

它会生成一个 sql 像

select doctor.name,.... from doctorpayment inner join doctor on ... where ...

老实说,我的直觉是您可能过早地进行了优化。除非您已经分析了您的软件并确定只获取一列而不是所有列对性能至关重要,否则我不会费心去优化它。

但是,要回答您的问题:您可以像这样让 EF 检索单个列:

var name=dbContext.Doctors.Where(d=>d.ID==DoctorId).Select(d=>d.Name)

当然,如果您经常需要访问它,您也可以将其封装在 DoctorPayment class 中的只读 属性 中。

请注意,这种方法的缺点是您总是从数据库中获取名称,即使之前的查询可能已经通过延迟加载预取了 Doctor 实体。

实体目前无法做到这一点Framework.EF是否支持对象映射Only.You无法使用 EF 映射单列。

唯一可能的方法是获取整个对象的映射,即医生,然后您可以使用 EF select 仅获取名称 即

var DoctorName=DoctorPayment.Doctor.Name