0

私は 2 つの EF タイプ、研究と患者を持っています。スタディには多くの患者を含めることができます。特定の研究から患者のリストを返したいので、次のようなメソッドがあります。

public IEnumerable<Patient> GetPatientsByStudyId(int id)
{
    return Context.Studies.Where(e => e.StudyId == id).Select(s => s.Patients).First();
}

これは機能しますが、最後に First() 呼び出しがあるため、確かに奇妙に見えます。私はそれを正しくしていないように感じます。これを行うためのより明確またはより正しい方法はありますか?

4

1 に答える 1

0

次のように書くことができます:

public IEnumerable<Patient> GetPatientsByStudyId(int id)
{
    return Context.Studies.Single(e => e.StudyId == id).Patients;
}

これにより、目的のスタディが取得され、このスタディに関連するすべての患者が選択されます。もちろん、id パラメータが有効であることを確認する必要があります。次のコードは、不要な例外の発生を防ぎます。

public IEnumerable<Patient> GetPatientsByStudyId(int id)
{
    Study selectedStudy = Context.Studies.SingleOrDefault(e => e.StudyId == id);
    return selectedStudy == null ? null : selectedStudy.Patients;
}

(または、必要に応じてEnumerable.Empty<Patient>()代わりに)null

于 2013-10-22T22:06:14.877 に答える