返回具有子表集合的实体

时间:2017-02-28 07:27:52

标签: entity-framework

这就是我所拥有的:

public class StudentHealthInfoType
{

    public int StudentHealthInfoId { get; set; }
    public bool? HasAllergies { get; set; }
    public List<HealthInfoMedicationType> HealthInfoMedicationType { get; set;}
}

public class HealthInfoMedicationType
{
    public int HealthInfoMedicationId { get; set; }
    public string MedicationName { get; set; }
}

var result = (from u in context.StudentHealthInfos
                  from m in context.HealthInfoMedications
                  where u.RegistrationId == registrationId
                   && u.StudentHealthInfoId == m.StudentHealthInfoId
                   select new StudentHealthInfoType 
                   { StudentHealthInfoId =     u.StudentHealthInfoId,
                      HasAllergies = u.HasAllergies,                                                                    HealthInfoMedicationType = new HealthInfoMedicationType
                     { HealthInfoMedicationId = m.HealthInfoMedicationId,
                       MedicationName = m.MedicationName
                      }                                                                   
                    }).FirstOrDefault();

我收到此错误,显示在HealthInfoMedicationType = new HealthInfoMedicationType

  

无法隐式转换类型   &#39; Dis.QueryManager.HealthFormTypes.HealthInfoMedicationType&#39;至   &#39; System.Collections.Generic.List&#39;

HealthInfoMedicationType需要是为一个StudentHealthInfoType记录返回的项目的集合。我如何设置我的对象然后投射它们以便这个查询有效?

1 个答案:

答案 0 :(得分:0)

如果您想查询特定的注册ID以及您可以这样做的HealthInfoMedications列表,请尝试此操作。

var result = context.StudentHealthInfos
         .Include(x=>x.HealthInfoMedicationType).FirstOrDefault(f => f.RegistrationId == 1);

//结果将是带有HealthInfoMedicationType列表的StudentHealthInfoType