Linq groupby orderby and join together

问题描述 投票:0回答:1

我有两个表Appointments和Patients,考虑它们的数据如下。请找到数据库的模式

attached image

以上是我的表格与数据。我的情况是,我必须得到一个特定的医生的病人。下面的查询工作,但不给独特的结果。我得到相同的病人数据不止一次,我可以使用独特的检索结果后,但我必须执行的操作在行查询本身(在db本身

from a in dbContext.Appointments
where a.doctorid == mydoctorid 
join p in dbContext.Patients on a.patientid equals p.patientid
order by p.name

updated code which led to exception

(from p in this.dbContext.Patients
join b in ( from a in this.dbContext.Appointments
            join p in this.dbcontext.Patient on a.Patientid equals p.id
            where a.doctorid == doctorid
            group a by a.Patientid into pg)
            on p.Patientid equals b.FirstOrDefault().Patientid
            order by p.Name
            select new { p.Patientid, p.Name }).ToList()

final code which i tried:

            (from p in this.m_dbContext.Patient
            join b in (from a in this.m_dbContext.Appointments
            join p in this.m_dbContext.Patient on a.Patientid equals 
            p.Patientid
            where a.Doctorid == doctorid && a.Clinicid == clinicid
            group a by a.Patientid)
            on p.Patientid equals b.FirstOrDefault().Patientid
            orderby p.Name
            select new
            {
              p.Patientid,
              p.Clinicid,
              p.Name,
              p.Mobilenumber,
              p.Gender,
              p.Dob,
              p.Age,
              p.Address,
              p.City,
              p.State,
              p.Pincode
           }).ToList().Count();

异常。

LINQ表达式 "FirstOrDefault(GroupByShaperExpression:KeySelector: a.patientid, ElementSelector:EntityShaperExpression: EntityType: Appointments ValueBufferExpression.InputionBindingExpression: a.patientid, ElementSelector:EntityShaperExpression: EntityType: Appointments ValueBufferExpression: ProjectionBindingExpression.EmptyProjectionMember.EmptyProjectionBindingExpression:KeySelector: a.patientid, ElementSelector:EntityShaperExpression: EntityType: Appointments ValueBufferExpression:ProjectionBindingExpression: EmptyProjectionMember IsNullable.False)'无法翻译成'A.patientid, ElementSelector:EntityShaperExpression: EntityType: Appointments ValueBufferExpression: ProjectionBindingExpression: EmptyProjectionMember IsNullable: False)'无法翻译。要么以可以翻译的形式重写查询,要么通过插入对AsEnumerable()、AsyncEnumerable()、ToList()或ToListAsync()的调用,显式地切换到客户端评估。请看 https:/go.microsoft.comfwlink?linkid=2101038。 以获取更多信息。

c# .net entity-framework linq .net-core
1个回答
1
投票

模式的命名约定略有不同,但你可以通过以下查询得到你想要的输出。

这个查询使用组获取所有独特的病人,然后通过子查询获取名字。

考虑将p.Id改为p.PatientId。

from p in dbContext.Patients
join b in (from a in dbContext.Appointments
      join p in dbContext.Patients on a.PatientId equals p.Id
      where a.DoctorId == mydoctorId
      group a by a.PatientId)
on p.Id equals b.FirstOrDefault().PatientId
select new {p.Id, p.Name}


© www.soinside.com 2019 - 2024. All rights reserved.