如何使用EF在c#中使用lambda表达式连接?

时间:2017-06-07 11:22:48

标签: c# entity-framework linq

我想用lambda表达式做左联接。但我不知道我该怎么做。我尝试了很多LINQ查询,但没有得到正确的查询。我是实体框架的新手。所以任何知道我怎么做的人都请告诉我。

下面我尝试了这个查询:

var query = UsersContext.Users.OrderBy(a => a.Email).Skip(skip).Take(pageSize).ToList();
var result = (from u in db.Notification
              join c in query on u.id equals c.Id into j1
              from j2 in j1.DefaultIfEmpty()
              select new { u, j2 }).OrderByDescending(a => a.u.datetime).Take(3).ToList();

这是我的查询。我想让它加入通知表,只获得最后3个通知。

1 个答案:

答案 0 :(得分:0)

var query = UsersContext.Users.Blah().Blah().ToList();
 // It's a non-complete List of Users....  (all we care about)

 var ids = query.Select(u=>u.Id).ToArray();
 // get an array of needed Users.

var notes = (from u in db.Notification
              where ids.Contains(u.id)
              select u).ToList(); 

var results = from u in notes
          join c in query on u.id equals c.Id into j1
          from j2 in j1.DefaultIfEmpty()
          select new { u, j2 }).OrderByDescending(a => a.u.datetime).Take(3).ToList();