使用 LINQ 和 Lambda 加入/在哪里

Join/Where with LINQ and Lambda(使用 LINQ 和 Lambda 加入/在哪里)
本文介绍了使用 LINQ 和 Lambda 加入/在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I'm having trouble with a query written in LINQ and Lambda. So far, I'm getting a lot of errors here's my code:

int id = 1;
var query = database.Posts.Join(database.Post_Metas,
                                post => database.Posts.Where(x => x.ID == id),
                                meta => database.Post_Metas.Where(x => x.Post_ID == id),
                                (post, meta) => new { Post = post, Meta = meta });

I'm new to using LINQ, so I'm not sure if this query is correct.

解决方案

I find that if you're familiar with SQL syntax, using the LINQ query syntax is much clearer, more natural, and makes it easier to spot errors:

var id = 1;
var query =
   from post in database.Posts
   join meta in database.Post_Metas on post.ID equals meta.Post_ID
   where post.ID == id
   select new { Post = post, Meta = meta };

If you're really stuck on using lambdas though, your syntax is quite a bit off. Here's the same query, using the LINQ extension methods:

var id = 1;
var query = database.Posts    // your starting point - table in the "from" statement
   .Join(database.Post_Metas, // the source table of the inner join
      post => post.ID,        // Select the primary key (the first part of the "on" clause in an sql "join" statement)
      meta => meta.Post_ID,   // Select the foreign key (the second part of the "on" clause)
      (post, meta) => new { Post = post, Meta = meta }) // selection
   .Where(postAndMeta => postAndMeta.Post.ID == id);    // where statement

这篇关于使用 LINQ 和 Lambda 加入/在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to pass lambda #39;include#39; with multiple levels in Entity Framework Core?(如何在 Entity Framework Core 中传递具有多个级别的 lambda include?)
Getting all types that implement an interface(获取所有实现接口的类型)
Combining two expressions (Expressionlt;Funclt;T, boolgt;gt;)(组合两个表达式 (ExpressionFuncT, boolgt;))
Is there a reason for C##39;s reuse of the variable in a foreach?(C# 在 foreach 中重用变量是否有原因?)
Lambda/Linq with Contains criteria for multiple keywords(Lambda/LINQ WITH包含多个关键字的条件)
Is using quot;outquot; bad practice(正在使用OUT;OUTQOOT;坏做法)