2017-06-05 51 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 
    { 
     ... 
    });