Search code examples
c#sql-to-linq-conversion

SQL TO linq in c#


This code is from my sql query

SELECT Branchname
FROM Branch
WHERE NOT EXISTS (SELECT Branchname FROM vBranching 
WHERE Branch.Branchname = vBranching.Branchname AND UserName = 'xCuttiepies');

iwant to execute it into linq c# web api

Its look like this

var Branch = _dbcontext.Branches.Select(c => c.Branchname).ToList();
var vBranching = _dbcontext.VBranchings.Select(a => a.BranchName).ToList();
var ass = Branch.Where(!Branch.Exists(Branch == vBranching));
return Ok(vBranching);

In Branch == vBranching it says cannot convert from bool to System.Predicate<string>

I want to fetch the data that not exists on that different tables.


Solution

  • You souldn't be using ToList except right at the end, and your lambda syntax is off, and the equivalent of EXISTS is Any. You are also returning the wrong value.

    var Branches =
        _dbcontext.Branches
        .Where(b => !_dbcontext.VBranchings.Any(vb =>
            vb.BranchName == b.BranchName && vb.UserName == "xCuttiepies"))
        .Select(c => c.Branchname)
        .ToList();
    return Ok(Branches);