Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use Linq " NOT IN"

Tags:

c#

.net

linq

I'm using Entity Framework
So I want to write a sql command using two tables - tblContractor and tbSiteByCont tables. It looks like this in SQL

SELECT     PKConID, Fname, Lname
FROM         tblContractor
WHERE     (PKConID NOT IN
                          (SELECT     FKConID
                            FROM          tbSiteByCont
                            WHERE      (FKSiteID = 13)))

but I don't know how to write in Linq.

I tried like this

  var query1 = from s in db.tblSiteByConts   
                        where  s.FKSiteID == id
                        select s.FKConID;


            var query = from c in db.tblContractors   
                        where c.PKConID != query1.Any()
                        select Contractor;

But this doesn't work. So how should I write it? What is the procedure? I'm new to Linq.

like image 642
aruni Avatar asked Nov 29 '22 16:11

aruni


1 Answers

var _result = from a in tblContractor
              where !(from b in tbSiteByCont
                        where FKSiteID  == 13
                        select b.FKConID)
                        .Contains(a.PKConID)
              select a;

or

var siteLst = tbSiteByCont.Where(y => y.FKSiteID == 13)
                          .Select(x => x.FKConID);
var _result = tblContractor.Where(x => !siteLst.Contains(x.PKConID));
like image 86
John Woo Avatar answered Dec 19 '22 07:12

John Woo