2017-06-05 39 views
0

,我有以下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() 

我知道如何創建一個連接,使用我的映射,所以creati加入並不是問題。我也知道如何做我需要的日期功能,所以這不是問題。

我需要知道如何(使用LINQ方法)說,部分來完成:where Schedule.Time < SOMETHING

這是我已經試過了,但它拋出一個錯誤:

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

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

那麼,如何在連接表上實現「Where」,就像我可以在SQL中一樣,在實體框架中使用linq方法?

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

回答

2

喜歡的東西

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

context.Patient.Where(p => p.Schedules.Any(s => s.Time < DateTime.Now)); 
+0

哇,太好了!出於某種原因,我從來沒有想過要交換查詢,並從Schedule開始查詢。好的答案! –

1
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} 
0

首先,我不知道這是否是明智的做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 
    { 
     ... 
    });