0

I have an MVC app using Linq to Entities and I'm having a hard time figuring out how to get this part of a query written. This is an excerpt from a SQL Stored Procedure that works. I know I can use the procedure but I'm trying to get a better understanding of LINQ. The goal is to get the last Routing for a requisition and the ReqRoutingID is an identity filed so the last entry in the table is always the one I want.

SELECT h.ReqID, rr.RoutingSectionID FROM LOG_ReqHeader h JOIN dbo.Log_ReqRoutings rr ON rr.ReqRoutingID = ( SELECT TOP 1 r.ReqRoutingID FROM Log_ReqRoutings r1 WHERE r1.ReqID = h.ReqID ORDER BY r1.ReqRoutingID desc) 
6
  • I think your query missing SELECT part Commented Jan 28, 2013 at 20:22
  • @Lazyberezovsky, I realize that I had not indicated which part I am having trouble with. It is the Join part that I am having trouble with. I edited the post to include the SELECT part so it makes more sense. Thanks. Commented Jan 28, 2013 at 21:21
  • Could you post your entities? Commented Jan 28, 2013 at 21:22
  • ReqRoutingID is a key of Log_RequRoutings table? Commented Jan 28, 2013 at 21:23
  • @Lazyberezovsky, I'm confused because you had posted an answer that worked but now the post says it has been deleted. Commented Jan 28, 2013 at 22:34

1 Answer 1

3
var query = from h in db.LOG_ReqHeader from rr in db.Log_RequRoutings where rr.ReqRoutingID == (from r1 in db.Log_RequRoutings where r1.Req == h.ReqID orderby r1.ReqRoutingID descending select r1).FirstOrDefault().ReqRoutingID select new { h.ReqID, rr.RoutingSectionID }; 
Sign up to request clarification or add additional context in comments.

5 Comments

Sorry, don't remember now if First is supported by EF (FirstOrDefault is definitely supported). You can give it a try
If FirstOrDefault() returns null wont that give exception on accessing ReqRoutingID ?
@Magnus whole query is translated into SQL, so there will not be any exceptions here
This answer worked once I cleaned up things like removing the extra "u" from Log_RequRoutings. What confuses me is the fact that there are two from statements. This is the first time I have come across a statement like this.
@AlanFisher yes, there is no problem with several from statements. Actually it is the only way you can do join with conditions in Linq

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.