簡體   English   中英

如何使用實體框架在聯接表上完成位置

[英]How to Accomplish a Where on a joined table with Entity Framework

我的數據庫中有以下2個表:

[Schedule](
    [Time] [datetime] NULL,
    [ScheduleID] [bigint] IDENTITY(1,1) NOT NULL,
    [PatientID] [varchar](20) NULL,
 CONSTRAINT [PK_Schedule] PRIMARY KEY CLUSTERED 
(
    [ScheduleID] ASC
)

和:

[Patient](
    [NameLast] [varchar](20) NOT NULL,
    [NameMiddle] [varchar](20) NULL,
    [NameFirst] [varchar](20) NOT NULL,
    [DOB] [varchar](20) NULL,
    [PatientID] [varchar](20) NOT NULL,
 CONSTRAINT [PK_Patient] PRIMARY KEY CLUSTERED 
(
    [PatientID] ASC
)

我想完成以下SQL,除了在實體框架中使用linq方法外:

select NameFirst, NameLast, DOB
from Patient
join Schedule on Schedule.PatientID = Patient.PatientID
where Schedule.Time < GETDATE()

我知道如何使用映射創建聯接,所以創建聯接不是問題。 我也知道如何做我需要的日期功能,所以這不是問題。

我需要知道如何完成(使用linq方法)該部分的內容: where Schedule.Time < SOMETHING

這是我嘗試過的方法,但引發了錯誤:

var patients = context.Patient
    .Include(x =>
        x.Schedule.Where(y => y.Time < DateTime.Now)
    );

它給我的錯誤是:“包含路徑表達式必須引用在類型上定義的導航屬性。”

因此,如何像使用SQL在SQL中一樣使用Entity Framework的linq方法來完成聯接表上的“哪里”呢?

我不能做context.Patients.Where(x => x.Schedules.Time == DateTime.Now); 因為Patient.Schedules是一個集合,因為這是一對多的關系。

就像是

context.Schedule.Where(y => y.Time < DateTime.Now).Select( s => s.Patient);

要么

context.Patient.Where( p => p.Schedules.Any( s => s.Time < DateTime.Now) );
from t1 in db.Patient 
join t2 in db.Schedule on 
t1.PatientId equals t2.PatientId 
where t2.Time<getTime 
select new { t1.NameFirst, t1.NameLast, t1.DOB}

首先,我不確定在查詢中執行GetDate()是否明智,因為IQueryable我認為這行不通,而IEnumerable我不確定在查詢期間將其調用多少次。列舉。

您可以首先過濾要使用的日程表,然后進行聯接。

小步驟:

DateTime myDate = GetDate();
var oldSchedules = dbCntext.Schedules.Where(schedule => schedule.Time < myDate);

var requiredResult = dbContext.Patients  // join Patients
    .join(oldSchedules,                  // with the old schedules
    patient => patient.PatientID,        // from patients take PatientID
    schedule => schedule.PatientID<      // from old schedules that PatientID
    (patient, schedule) => new           // when they match, take the recods
    {                                    // to create a new Anonymous type
        NameFirst = patient.NameFirst,   // with the required properties 
        NameLast = patient.NameLast,
        Dob = patient.Dob,
    });

當然,您可以將其放在一個語句中(GetDate()除外)

DateTime myDate = GetDate();
var result = dbContext.Schedules
    .Where(schedule => schedule.Time < myDate)
    .Join(dbContext.Patients,
    schedule => schedule.PatientId,
    patient => patient.PatientId,
    (schedule, patient) => new
    {
        ...
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM