如何使这个LINQ语句更优雅?

时间:2014-03-06 18:47:21

标签: linq entity-framework

医生到OfficeStaff的关系是多对多的。当我添加办公室职员时,我想确保分配给该实体的赞助医师的ID目前已在数据库中,所以我这样做:

foreach (var sponsoringPhysician in officeStaff.Physicians)
{
    if (!container.Physician.Any(q => q.Equals(sponsoringPhysician)))
        throw new ApplicationException("A sponsoring physician is not found for staff: " + user.AccountName);
}

等式检查设置为根据ID

进行检查。

如何用子查询替换foreach中的代码?

2 个答案:

答案 0 :(得分:2)

怎么样?
var hasNoSponsor = officeStaff.Physicians.FirstOrDefault(p => !container.Physician.Any(q => q.Equals(p)));
if (hasNoSponsor != null) throw new ApplicationException("A sponsoring physician is not found for staff: " + user.AccountName);

编辑:我认为这可以进一步简化为:

if (!container.Physician.Any(p => officeStaff.Physicians.Contains(p))) {
    throw new ApplicationException("A sponsoring physician is not found for staff: " + user.AccountName);
}

- 请注意Contains使用Equals进行相等比较。

答案 1 :(得分:1)

未经测试:

if(officeStaff.Physicians.
         Join(container.Physician,
           po => po.ID, pc => pc.ID, 
           (po,pc)=>new {po}).
           Where(po.Equals(pc)).Any()
     ){
     throw new ApplicationException("A sponsoring physician is not found for staff: " + user.AccountName);
   }