c# - Linq groupby orderby 和 join 一起
问题描述
我有两个表 Appointments 和 Patients,考虑他们以以下方式拥有数据:请在
以上是我的数据表。我的情况是我必须让患者了解特定的医生。下面的查询有效,但没有给出不同的结果。我不止一次获得相同的患者数据,我可以在检索结果后使用 distinct,但我必须在行查询本身中执行操作(在数据库本身中)
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: ProjectionBindingExpression: EmptyProjectionMember IsNullable: False)'。以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估。有关详细信息,请参阅https://go.microsoft.com/fwlink/?linkid=2101038。
解决方案
架构命名约定略有不同,但您可以通过以下查询获得所需的输出。
此查询使用 group by 获取所有唯一患者,然后通过子查询获取名称。
考虑将 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}
推荐阅读
- php - 我的表单中有 3 个日期范围选择器我想存储 00-00-0000 00-00-0000
- c - 具有无限多(未命名)参数的函数 - 如何正确访问这些参数?
- reactjs - 构建 react-app 的意外结果
- ios - 如何在 Swift 中使用可解码?
- c++ - 如何在 iOS 上跟踪 C++ 内存分配?
- c# - 需要 C# datagrid 视图中 Quantity 列的默认值的帮助,它应该是可变的
- android-studio - Android Studio 3.2.1 找不到资源错误
- javascript - sqlite3 插入或更新
- directx - DirectX 11 ID3DDevice::CreateTexture2D 初始数据失败
- python - 如何恢复 rsa 公钥?或在python中将字节更改为rsa公钥?