使用LINQ更新,并在运算符选择中

时间:2015-01-11 11:40:56

标签: c# linq

我尝试将SP转换为linq查询

这是我的SP:

UPDATE PatientAlertsSummary
SET IsViewed =1 
WHERE  PatientID IN (SELECT PatientID FROM PatientTherapist WHERE TherapistID=@TherapistID)

我试图创建一个查询linq代码,这是(到目前为止)我的linq查询: 这样做我遇到了一些困难

var query = from pas in context.PatientAlertsSummaries
                         where pas.PatientID.Contains(from pt in context.PatientTherapists where pt.TherapistID == therapistid  )
                            select pas;

                        foreach (var item in query)
                        {
                            item.IsViewed = true;
                        }

我怎样才能做对?

2 个答案:

答案 0 :(得分:0)

您可以更改查询以加入表以检索所需的结果,然后相应地更新记录:

var query = from pas in context.PatientAlertsSummaries
join pt in context.PatientTherapists on pas.PatientID equals pt.PatientID
where pt.TherapistID == therapistid
select pas;

foreach (var item in query)
{
    item.IsViewed = true;
}

显然这是未经测试的,并且基于您当前的sql / linq查询。

答案 1 :(得分:0)

您可以这样做:

    public class PatientAlertsSummary
    {
        public bool IsViewed;
        public int PatientID;
    }

    public class PatientTherapist
    {
        public int PatientID;
        public int TherapistID;
    }

    public void UpdateIsViewed(PatientAlertsSummary summary)
    {
        summary.IsViewed = true;
    }

    [TestMethod]
    public void Test1()
    {
        //UPDATE PatientAlertsSummary
        //SET IsViewed =1 
        //WHERE  PatientID IN (SELECT PatientID FROM PatientTherapist WHERE TherapistID=@TherapistID)

        var therapistId = 1;

        var patientAlertsSummaries = new List<PatientAlertsSummary>() { 
            new PatientAlertsSummary(){PatientID = 1},
            new PatientAlertsSummary(){PatientID = 2},
            new PatientAlertsSummary(){PatientID = 3}
        };

        var PatientTherapists = new List<PatientTherapist>() { 
            new PatientTherapist(){PatientID = 1 , TherapistID = 1},
            new PatientTherapist(){PatientID = 2 , TherapistID = 1},
            new PatientTherapist(){PatientID = 3, TherapistID = 2}
        };

        var updatedPatinets1 = PatientTherapists.
            Where(o => o.TherapistID == therapistId).
            Join(patientAlertsSummaries,
            patientTherapist => patientTherapist.PatientID,
            patientAlertsSummary => patientAlertsSummary.PatientID,
            (o, p) => 
                {
                    UpdateIsViewed(p);
                    return p;
                }).ToList();

    }