我有两个实体医生(父母)和DoctorPayment(孩子)
一种可能的方法是在DoctorPayment实体中获取Doctor对象并通过Doctor.Name
但是我只需要DoctorName中的DoctorName而不是整个对象,应该由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
}
答案 0 :(得分:3)
说实话,我的预感是你可能过早地进行了优化。除非您已经对您的软件进行了分析并确定只提取一个而不是所有列对性能至关重要,否则我不打算优化它。
但是,要回答您的问题:您可以使EF检索单个列,如下所示:
var name=dbContext.Doctors.Where(d=>d.ID==DoctorId).Select(d=>d.Name)
当然,如果你经常需要访问它,你也可以将它封装在DoctorPayment类的只读属性中。
请注意,这种方法的缺点是您总是从DB中获取Name,即使Doctor实体可能已经通过先前查询的延迟加载预取。
答案 1 :(得分:1)
目前不可能使用Entity Framework.EF仅支持对象映射。您无法使用EF映射单列。
只有Posssible方式是为整个对象获取Maping,即Doctor,然后你可以使用EF select来获取Name 即
var DoctorName=DoctorPayment.Doctor.Name
答案 2 :(得分:0)
db.DoctorPayment.Include(x=>x.Doctor).Where(...).Select(x=>new{docName=x.Doctor.Name,.....})
它会生成一个像
这样的sqlselect doctor.name,.... from doctorpayment inner join doctor on ... where ...