将包含select的where子句转换为Linq

时间:2018-08-28 12:52:15

标签: sql-server linq

我需要将以下SQL转换为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
)

但是我不知道如何进行。有帮助吗?

2 个答案:

答案 0 :(得分: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); 
}

但是,通过猜测,b.Id是Branchs的主键,并且通过外键bId与Actions相关。然后:

var result =  db.Branches
              .FirstOrDefault(b => b.Actions
                                    .Where(a => a.aId = 10596)
                                    .OrderByDescending(a => a.CreateDate));

答案 1 :(得分:1)

var result = Branches
        .Where(b => b.ID == Actions.Where(w => w.aId == 10596 && w.bId != null)
        ?.OrderByDescending(o => o.createDate)
        .First()?.bId);