使用连接方法和 lambdas 连接实体框架 [英] Entityframework Join using join method and lambdas

查看:22
本文介绍了使用连接方法和 lambdas 连接实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎有不同的方法可以使用 linq 进行连接.一种更直接,只涉及像这样连接表:

It seems there are different ways to do joins using linq. One is more straightforward and involves just joining tables like this:

var found = from c in s.categories
            join cm in s.categorymaps on c.CategoryId equals cm.ChildCategoryId
            select c;

还有另一种使用 lambdas 的方法,我有很多时间试图弄清楚如何使用这种语法进行连接.谁能提供详细解释和大量示例的链接?或者只是简单地使用示例演示如何使用这种相当混乱的语法?

There is another way using lambdas and I'm having a heck of a time trying to figure out how to join using this syntax. Can anyone provide links to detailed explanations and lots of examples? Or just simply demonstrate using examples how to use this rather confusing syntax?

var x = _session.All<category>().Join<categorymap,category, ....

推荐答案

通常我更喜欢 LINQ 的 lambda 语法,但 Join 是我更喜欢查询语法的一个例子 - 纯粹是为了可读性.

Generally i prefer the lambda syntax with LINQ, but Join is one example where i prefer the query syntax - purely for readability.

尽管如此,这相当于您的上述查询(我认为,未经测试):

Nonetheless, here is the equivalent of your above query (i think, untested):

var query = db.Categories         // source
   .Join(db.CategoryMaps,         // target
      c => c.CategoryId,          // FK
      cm => cm.ChildCategoryId,   // PK
      (c, cm) => new { Category = c, CategoryMaps = cm }) // project result
   .Select(x => x.Category);  // select result

您可能需要根据您想要返回的内容来调整投影,但这就是它的要点.

You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.

这篇关于使用连接方法和 lambdas 连接实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆