【问题标题】:Converting query to lambda expression with joins and where clause使用连接和 where 子句将查询转换为 lambda 表达式
【发布时间】:2015-08-06 16:15:18
【问题描述】:

我有这个查询,但在转换为 lambda 表达式时遇到问题

SELECT [dbo].[Prospects].[Id]
  ,[UserId]
  ,[NewId]
  ,[dbo].[Prospects].[Status]
  FROM [dbo].[Prospects]  join [dbo].[User] on [dbo].[User].Id = [dbo].      [Prospects].UserId
  where [dbo].[Prospects].NewId = 3 and [dbo].[User].IsActive = 1

这是我得到的,但它不起作用

 var result = Workspace.Prospects.Join
            (Workspace.Users, pros => pros.UserId,
            use => use.Id, (pros, use)
            => new { Prospect = pros, User = use}).Where
            (both => both.User.IsActive == true && both.Prospect.NewId == idVacante)
            .OrderBy(both => both.Prospect.Id).AsEnumerable().ToList();
 List<Prospect> prospects = result.Cast<Prospect>().ToList();

【问题讨论】:

  • 不工作怎么办?没有返回正确的结果?不编译?抛出异常?
  • 抛出了哪个异常?或者它只是没有得到预期的行?
  • 对不起,我不够具体,我没有得到预期的行。我需要正确选择字段。我收到这条消息 Test 'RecruitmentTestLab.TestLab.Prospects.CheckProspectsVacancies' failed: System.InvalidCastException : Unable to cast object of type 'f__AnonymousType1`4[System.Int32,System.Int32,System.Int32,System. Int32]' 输入'RecruitmentTestLab.Prospect'。

标签: c# .net sql-server lambda


【解决方案1】:

这并不难。您可以在加入表格之前过滤表格

var result = Workspace.Prospects.Where(x=> x.NewId == 3)
                  .Join(Workspace.Users.Where(x => x.IsActive == 1),
                          p => p.UserId,
                          u => u.Id,
                          (p, u) => new { p.Id, p.UserId, p.NewId, p.Status })

【讨论】:

    猜你喜欢
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 2015-04-14
    • 2020-10-25
    • 1970-01-01
    相关资源
    最近更新 更多