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

多表关联SQL转换为C# Lambda表达式的实现方法咨询

Converting Your SQL Join to C# Lambda Expressions

Alright, let's break this down step by step. Your SQL is joining three tables (Config, Family, and View) to pull the Name fields from Family and View. Assuming you're working with Entity Framework (the standard tool for this kind of ORM work in C#), here's how you can translate that query to Lambda expressions:

Basic Lambda Implementation

First, let's assume your DbContext has DbSet properties named Configs, Families, and Views, and your entity classes match the table structures (e.g., Config has Family_ID and View_ID, Family has ID and Name, View has ID and Name).

var result = Configs
    .Join(Families, 
          config => config.Family_ID, 
          family => family.ID, 
          (config, family) => new { Config = config, Family = family })
    .Join(Views, 
          combined => combined.Config.View_ID, 
          view => view.ID, 
          (combined, view) => new 
          {
              FamilyName = combined.Family.Name,
              ViewName = view.Name
          })
    .ToList();

Let's Break It Down

  • First Join: We start with the Configs set, then join it to Families using the Family_ID from Config and ID from Family. We bundle the matching Config and Family objects into an anonymous type to carry them forward.
  • Second Join: Next, we take that combined result and join it to Views, using View_ID from the original Config and ID from View.
  • Final Select: Finally, we project the results into a new anonymous type (or you could use a custom DTO class if you prefer) that contains just the two Name values you need.

Alternative: Using Query Syntax (Bonus!)

If Lambda feels a bit verbose for multiple joins, you might find LINQ query syntax more readable (it's closer to your original SQL):

var result = (from c in Configs
              join f in Families on c.Family_ID equals f.ID
              join v in Views on c.View_ID equals v.ID
              select new 
              {
                  FamilyName = f.Name,
                  ViewName = v.Name
              }).ToList();

Either approach will give you the exact same result as your SQL query. Just pick whichever feels more intuitive for you!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 22:02:44