使用Entity Framework返回2个表中的数据 [英] Return data from 2 tables with Entity Framework
问题描述
我正在使用MVC3和Entity Framework,但是到了需要从不同表中获取更多数据的地步.通常我会做这样的事情来从表中获取数据:
I'm working with MVC3 and Entity Framework but i came to a point where i need more data from different tables. Usually i'd do something like this to get data from a table:
Table: Users
id
username
在代码中,我将执行以下操作以获取所有用户:
In code i would do something like this to get all the users:
public static IEnumerable<Users> GetUsers( int userId )
{
MyEntities ent = new MyEntities();
return from g in ent.Users
where g.OwnerUserId == userId
select g;
}
所以这会让我所有的用户回来.
So this would give me all my users back.
但是用户可以加入一个组,而我必须从特定组中获取所有用户名.
But a user can join a group, and i have to get all the usernames from a specific group.
Table: userGroups
id
fk_user_id
fk_group_id
现在,如果我要使用此代码:
Now if i'd use this code:
public static IEnumerable<userGroups> GetUsersFromGroup( int groupId )
{
MyEntities ent = new MyEntities();
return from g in ent.userGroups
where g.OwnerUserId == userId
select g;
}
现在显然,这仅返回"userGroups"表中的数据.但是不知何故我也需要用户表中的用户名.我如何也可以获取这些数据,并且仍然以IEnumerable的形式返回我的"userGroups"?
Now obviously this only returns me the data from the "userGroups" table. But somehow i also need the username from the Users table. How can i get that data too and still return my "userGroups" as an IEnumerable?
在SQL中,我只是做一个LEFT JOIN,但是我真的不知道在这里是如何工作的.
In SQL i'd simply do a LEFT JOIN, but i can't really figure out how that works here.
推荐答案
类似这样的事情:
var query = from g in ent.userGroups
join u in ent.Users on g.fk_user_id equals u.userID
select new { g, u, });
或使用 LEFT JOIN
var query = (from g in ent.userGroups
from u in ent.Users.Where(a => a.fk_user_id == u.userID).DefaultIfEmpty()
select new { g, u, });
这篇关于使用Entity Framework返回2个表中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!