EF映射对象列表中的最新对象

时间:2016-09-22 22:50:54

标签: c# sql entity-framework linq mapping

我正在尝试执行此Linq查询:

dataContext.Request.Where(x => x.LatestResponse.IsReviewRequired);

问题是LatestResponseID实际上不是Request表上的列。

要获得LatestResponse,我必须执行此操作SQL

  SELECT ....
  FROM [doe].[Request] Req
      LEFT JOIN (
          SELECT MAX(ResponseID)
          FROM [doe].[Response]
          GROUP BY [RequestID]) AS Resp ON Req.[RequestID] = Resp.[RequestID]
      LEFT JOIN [doe].[Response] LatestResp ON Resp.[ResponseID] = LatestResp.[ResponseID]

我可以map吗?如果是这样,怎么样?

1 个答案:

答案 0 :(得分:1)

你可以这样做(如果你想要加入两边):

var results = dataContext.Requests.Select(request => new
        {
            Request = request,
            LatestResponse = request .Responses.FirstOrDefault(response => response .RequestID == request.Responses.Max(response2 => response2.RequestID))
        });

此外,如果您尝试重新获取请求对象,但是通过最新响应的属性对其进行过滤,则以下是一个示例:

var results = dataContext.Requests.Select(request => new
        {
            Request = request,
            LatestResponse = request.Responses.FirstOrDefault(response => response.RequestID == request.Responses.Max(response2 => response2.RequestID))
        }).Where(request => request.LatestResponse.MyProperty == "Value").Select(request => request.Request);