简体   繁体   English

如何在Entity Framework中进行适当的左连接

[英]How to do a proper left join in Entity Framework

This should be a really simple problem to solve, but for some reason Entity Framework makes it really hard for me. 这应该是一个非常简单的问题需要解决,但由于某些原因,实体框架对我来说真的很难。 I just need to do a simple left join... 我只需要做一个简单的左连接......

I have two tables. 我有两张桌子。 For example, a user table: 例如,用户表:

user_id | name | fk_group_id

And a group table 还有一张小组表

group_id | groupname

In raw SQL: 在原始SQL中:

SELECT * FROM users AS u
LEFT JOIN groups AS g
ON u.fk_group_id = g.group_id
WHERE groupname = 'my group'

Super easy in SQL. SQL中超级简单。 But when i search for answers on how to do this is Entity Framework, then there's one thing that immidiately goes through my mind... WTF...!?!? 但是,当我搜索关于如何做到这一点的答案是实体框架时,那么有一件事情会在我脑海中浮现...... WTF ......!?!? Super large constructed, weird formatted "queries" are performed and i'm really confused what i need and what not... 超大型构造,奇怪的格式化“查询”被执行,我真的很困惑我需要什么,不是什么...

So i'm hoping someone could help me with my specific problem. 所以我希望有人可以帮我解决我的具体问题。 How would one rewrite the above SQL query in (LINQ?) Entity Framework. 如何在(LINQ?)Entity Framework中重写上述SQL查询。

Currently i have this: 目前我有这个:

var bla = (from m in myEnt.Users
          // My join attempt..
          join mp in myEnt.Groups on m equals mp.group_id into n
          where n.group_name == "something"
          select m);

Even if this was working, i really don't see how this is suppose to make my life easier.. Oo 即使这是有效的,我也真的不知道如何让我的生活变得更轻松。噢

Anyway, i really hope someone can help me out :-) 无论如何,我真的希望有人可以帮助我:-)

why do you need a join? 为什么你需要加入? isn't there a relation between users and groups already? 用户和群组之间是否存在关系?

var bla = from m in myEnt.Users
           where m.Group.Groupname = "something"
           select m;

this should do just fine or am i wrong? 这应该做得好还是我错了?

Umm, you don't have to explicitly do that with any ORM. 嗯,你不必用任何ORM明确地这样做。 That's the catch here, that's what mapping's for. 这就是这里的问题,这就是映射的目的。

You can just go: 你可以去:

var blah = myEnt.Users.Where(user => user.Group.Name == "something");

Or in the alternate syntax 或者在替代语法中

from usr in myEnt.Users
where usr.Group.Name == "something"
select usr`

If it's many-to-one relationship after mapping to objects, then every User entity will have the navigation property to his Group , and every Group will have a User collection. 如果映射到对象后它是多对一关系,则每个User实体都将具有其Group的导航属性,并且每个Group都将具有User集合。 Then you only have to filter the results appropriately. 然后,您只需要适当地过滤结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM