EDIT: Simplified problem and clarified question.
I am trying to convert this Stored Procedure into a LINQ statement:
SELECT UserID, MAX(RowID) as RowID into #tempa
FROM Users
WHERE Approved = 1
GROUP BY UserID
SELECT (bunch of columns)
FROM Users INNER JOIN #tempa
ON (Users.UserID = #tempa.UserID AND Users.RowID = #tempa.RowID)
DROP TABLE #tempa
When I run this SPROC I get 292 rows. When I try to convert it to LINQ I do the following:
IQueryable<User> userQuery = db.Users.Where(x => x.Approved == true);
userQuery = userQuery.Where((x => x.RowID ==
db.Users.Where(u => u.UserID == x.UserID).Max(u => u.RowID)
));
IList<User> users = userQuery.ToList();
Result is 293 rows…
Now I change the SPROC to (it’s a bitmask where value 2 is active):
SELECT UserID, MAX(RowID) as RowID into #tempa
FROM Users
WHERE Approved = 1 AND (UserAttribtues & 2) = 2
GROUP BY UserID
SELECT (bunch of columns)
FROM Users INNER JOIN #tempa
ON (Users.UserID = #tempa.UserID AND Users.RowID = #tempa.RowID)
DROP TABLE #tempa
I get 289 rows with the sproc.
Try the following with LINQ:
IQueryable<User> userQuery = db.Users.Where(x => (x.UserAttributes & Convert.ToInt32(UserAttributes.Active)) == Convert.ToInt32(UserAttributes.Active) && x.Approved == true);
userQuery = userQuery.Where((x => x.RowID ==
db.Users.Where(u => u.UserID == x.UserID).Max(u => u.RowID)
));
Result is 127 rows….
At first I thought it was my use of .Max in the subquery, which AD.NET corrected me below, but the numbers are way off still, what am I missing here? I’m not understanding something…
Something like this should work, you can refactor out some predicates from this too.
You can try something like this:
Check that against the sql (strip out any other conditions please for debugging).
I think I missed the userId part, you’ll need to match the userId as well, otherwise it should not work properly. I am sure you can make the query a bit better, for example, use
letto keep the whole user object which has the highest rowid and then you can use the object to match both rowid and userid.