4
Answers

subQuery using Linq

S VK

S VK

7y
253
1
  1. // sql returns records  
  2.   
  3. SELECT * FROM InfoDetails WHERE InfoId =( SELECT tOP 1 InfoId FROM InfoMaster WHERE recordid=1 ORDER BY  CreationDate  DESC)  
  4.       
  5. // returns 0 records  
  6.   
  7.     db.InfoDetails.Where(u => u.InfoId ==(db.InfoMaster  
  8.                   .Where(x => x.recordid == Id).OrderByDescending(x => x.CreationDate).Select(x => x.InfoId).FirstOrDefault()))  
  9.                   .Select(t=> new InfoListViewModel  
  • i need the above sql as linq lambda expression

    sql returns reocrds but linq returns 0

Answers (4)
1
Nilesh Shah
NA 22.3k 215k 7y
your LINQ query seems to be correct,
however when you day the SQL query works but the LINQ does not, I want to highlight that in SQL Query you have used recordid = 1 which may be returning record as there are records with recordid = 1
while in LINQ you are using a variable, make sure to run the SQL query with value of that variable, may be there are no records in table with that id being passed to LINQ?
0
S VK
NA 18 0 7y
i tried by hardcoding the value also but still no results
0
S VK
NA 18 0 7y
both the replies r giving count as 0
0
Tapan Patel
NA 8.1k 101k 7y
Can you try something like this?
 
  1. var id = db.InfoMaster.Where(x1 => x1.recordid == 1).OrderByDescending(x2 => x2.CreationDate).Select(x3 => x3.InfoId).FirstOrDefault();  
  2.   
  3. var record =db.InfoDetails.Where(u => u.InfoId == id);