You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将指定多表关联SQL查询转换为LINQ查询语法与Lambda语法?

Converting Your Multi-Table Inner Join SQL to LINQ

I’ll break this down into both LINQ query syntax (the readable, SQL-like format) and Lambda method syntax, matching your exact select columns and join logic.

LINQ Query Syntax

This format closely mirrors your original SQL structure, making it easy to map and understand:

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

LINQ Lambda Method Syntax

If you prefer method chaining with lambda expressions, here’s the equivalent implementation:

var query = dbContext.Claims
    .Join(dbContext.Stores,
          claim => claim.StoreId,
          store => store.StoreId,
          (claim, store) => new { claim, store })
    .Join(dbContext.ClaimPatients,
          cs => cs.claim.ClaimId,
          cp => cp.ClaimId,
          (cs, cp) => new { cs.claim, cs.store, cp })
    .Join(dbContext.Patients,
          cscp => cscp.cp.PatientId,
          patient => patient.PatientId,
          (cscp, patient) => new 
          {
              ClaimId = cscp.claim.ClaimId,
              Ncpdp = cscp.store.Ncpdp,
              RxNumber = cscp.claim.RxNumber,
              RefillNumber = cscp.claim.RefillNumber,
              StoreId = cscp.store.StoreId,
              FirstName = patient.FirstName,
              MiddleNameInitial = patient.MiddleNameInitial,
              LastName = patient.LastName,
              NameSuffix = patient.NameSuffix
          });

Quick Notes:

  • Replace dbContext with your actual DbContext instance name.
  • The entity set names (like Claims, Stores) should match what’s defined in your DbContext (pluralized table names are the standard convention).
  • Both versions will generate SQL identical to your original query when executed (e.g., when calling .ToList() or iterating over the result).

内容的提问来源于stack exchange,提问作者Mike Henry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:48:35