[英]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.