我在使用 LINQ 和 Lambda 编写的查询时遇到问题。到目前为止,我遇到了很多错误,这是我的代码:
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 });
我是使用 LINQ 的新手,所以我不确定这个查询是否正确。
我发现如果你熟悉 SQL 语法,使用 LINQ 查询语法会更清晰、更自然,并且更容易发现错误:
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 };
但是,如果您真的坚持使用 lambda,那么您的语法就有点偏离了。这是使用 LINQ 扩展方法的相同查询:
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