0

I need to convert the following SQL to Linq:

select b.*
from Branches b
where b.Id = (select top 1 bId
from Actions a
where a.aId = 10596
and a.bId is not null
order by a.createDate desc
)

But I have no idea of how to proceed. Any help pls?

refresh
  • 1,319
  • 2
  • 20
  • 71
  • 1
    Perhaps my [SQL to LINQ Recipe](https://stackoverflow.com/questions/49245160/sql-to-linq-with-multiple-join-count-and-left-join/49245786#49245786) would help you? – NetMage Aug 28 '18 at 16:04

2 Answers2

1
var action = db.Actions
           .OrderByDescending(a => a.CreateDate)
           .FirstOrDefault(a => a.aId = 10596 && a.bId != DbNull.Value);
if (action != null)
{
   var result = db.Branches.Where(b => b.Id == action.bId); 
}

However, by guess b.Id is primary key for Branches and is related to Actions through foreign key bId. Then:

var result =  db.Branches
              .FirstOrDefault(b => b.Actions
                                    .Where(a => a.aId = 10596)
                                    .OrderByDescending(a => a.CreateDate));
Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39
1
var result = Branches
        .Where(b => b.ID == Actions.Where(w => w.aId == 10596 && w.bId != null)
        ?.OrderByDescending(o => o.createDate)
        .First()?.bId);  
Mojtaba Tajik
  • 1,725
  • 16
  • 34