多表关联SQL转换为C# Lambda表达式的实现方法咨询
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
Configsset, then join it toFamiliesusing theFamily_IDfromConfigandIDfromFamily. We bundle the matchingConfigandFamilyobjects into an anonymous type to carry them forward. - Second Join: Next, we take that combined result and join it to
Views, usingView_IDfrom the originalConfigandIDfromView. - 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
Namevalues 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

