LINQ(Normal和Lamba格式)中的复杂SQL连接

时间:2018-04-26 15:27:31

标签: c# linq

这是我的表格布局:

Table layout

这是我的SQL查询:

SELECT
  Claim.ClaimId,
  Store.Ncpdp,
  Claim.RxNumber,
  Claim.RefillNumber,
  Store.StoreId,
  Patient.FirstName,
  Patient.MiddleNameInitial,
  Patient.LastName,
  Patient.NameSuffix
FROM Claim
INNER JOIN Store
  ON Claim.StoreId = Store.StoreId
INNER JOIN ClaimPatient
  ON Claim.ClaimId = ClaimPatient.ClaimId
INNER JOIN Patient
  ON ClaimPatient.PatientId = Patient.PatientId

我如何在LINQ中以普通格式和Lambda格式编写它?

1 个答案:

答案 0 :(得分:0)

这是SQL查询的查询表达式(推荐使用lambda表达式,更容易处理):

var data = from claim in Claims
                   join store in Stores on claim.StoreId equals store.StoreId
                   join claimPatient in ClaimPatients on claim.ClaimId equals claimPatient.ClaimId
                   join patient in Patients on claimPatient.PatientId equals patient.PatientId
                   select new
                   {
                       claim.ClaimId,
                       store.Ncpdp,
                       claim.RxNumber,
                       claim.RefillNumber,
                       store.StoreId,
                       patient.FirstName,
                       patient.MiddleNameInitial,
                       patient.LastName,
                       patient.NameSuffix
                   };

修改

如果你想要它,那就是lambda版本:

var data =
            Claims.Join(Stores, claim => claim.StoreId, store => store.StoreId, (claim, store) =>
           new { claim.ClaimId, claim.RxNumber, claim.RefillNumber, store.Ncpdp, store.StoreId })

            .Join(ClaimPatients, claim => claim.ClaimId, cp => cp.ClaimId, (claim, cp) => 
            new { claim.ClaimId, claim.RxNumber, claim.RefillNumber, claim.Ncpdp,claim.StoreId, cp.PatientId })
            .Join(Patients, c => c.PatientId, p => p.PatientId, (c, p) => new
            {
                c.ClaimId,
                c.Ncpdp,
                c.RxNumber,
                c.RefillNumber,
                c.StoreId,
                p.FirstName,
                p.MiddleNameInitial,
                p.LastName,
                p.NameSuffix
            });