开发者

Is It Possible to do this T-SQL Query with LINQ (to Entities)

开发者 https://www.devze.com 2023-04-05 12:30 出处:网络
I\'m trying to write the following LINQ-Entities query: Get a list of Questions, that have been开发者_C百科 answered, ordered by most recently answered

I'm trying to write the following LINQ-Entities query:

Get a list of Questions, that have been开发者_C百科 answered, ordered by most recently answered

So, basically it's a 1..* between Question and Answer.

So i tried to write the query in SQL first, so that i understood it, and here's what i came up with:

WITH [Answers] AS
(
    SELECT      QuestionId,
                CreatedOn,
                ROW_NUMBER() OVER 
                (                        
                    PARTITION BY QuestionId
                    ORDER BY    CreatedOn DESC
                ) As [Rank]

    FROM    dbo.Answers
)

select a.*
from dbo.questions a
inner join answers on a.questionid = answers.questionid
where answers.rank = 1
order by answers.createdon desc

Now, i have no idea if it's even possible to do this with LINQ.

Of course, that query above might be the wrong way to go about it, so don't think of this as a simple T-SQL to LINQ-Entities translation.

I'm just looking for a way to write a LINQ-Entities query for the above requirement.

Any ideas?

EDIT

Here's what i've tried so far:

var query = questions
              .Where(q => q.Answers.Any())
              .OrderByDescending(
                q => q.Answers.OrderByDescending(
                  a => a.CreatedOn).FirstOrDefault());

Just hopeful i guess. Following error received:

DbSortClause expressions must have a type that is order comparable. Parameter name: key

EDIT

I should also mention that i need to eager load the Answers in the final result set, e.g:

return ctx.Questions.Include(q => q.Answers)


from question in context.Questions
where question.Answers.Any()
let max = question.Answers.Max(a=>a.CreatedOn)
orderby max descending
select question

EDIT: since you want to eager load answers; you might want to either resort to doing this entire query in SQL Server and exposing it to EF as a stored procedure or you might want to add LastAnswerOn column in questions table. This will make your query much more efficient and simple and you will be able to use it in EF without problems.


Replace that FirstOrDefault which does not make sense with First. Or Replace entire sub-query with Max (on date). It should work.

Good luck with EF, it is so broken ;-) In many cases where Linq To Sql would work, with EF I had to give up and fetch the data and do the computation locally.

0

精彩评论

暂无评论...
验证码 换一张
取 消