简体   繁体   中英

LINQ Query which is using a query in where clause

I want to achieve the below scenario...

Table 1 - tAccessRequest of Database 1 columns - RequestId, CardNo and so on...... Table 2 - tBadge of Database 2 Columns - CardNo, CardStatus and so on...

I created a Request Class as below

public class RequestDetails
{
    public int RequestID { get; set; }

    public int RequestTypeID { get; set; }

    public string PersonID { get; set; }

    public int SectionCode { get; set; }

    public int RequestStateID { get; set; }

    public int ApprovalStatusID { get; set; }
}

Now I am writing two LINQ query

List< RequestDetails > listReq = new List< RequestDetails >();

listReq = (from PP in DB1.tAccessRequests
                               where (PP.RequestStateID == 1 || PP.ApprovalStatusID == 1) && PP.SectionCode != null
                               select new RequestDetails
                               {
                                   RequestID = PP.RequestID,
                                   SectionCode = PP.SectionCode.Value 
                               }).ToList();

In the second LINQ query I want to achieve

var CardNoList = (from BC in prowatchContext.BADGE_C 
                                               where BC.STAT_COD != 'A' && BC.CARDNO in ("Select SectionCodefrom listReq"))

How to write the second LINQ query..

Please help

You just use Contains for IN :

var CardNoList = (from BC in prowatchContext.BADGE_C 
                  where BC.STAT_COD != 'A' &&
                        listReq.Select(lr => lr.SectionCode).Contains(BC.CARDNO)
                  ).ToList();

Note: If listReq is large this may not work unless you do the Contains test on the client, in which case you may want to use a HashSet :

var reqCardNos = new HashSet<int>(listReq.Select(lr => lr.SectionCode));

var CardNoList = prowatchContext.BADGE_C.Where(BC => BC.STAT_COD != 'A')
                                        .AsEnumerable()
                                        .Where(BC => reqCardNos.Contains(BC.CARDNO))
                                        .ToList();

The AsEnumerable will pull all the matching rows to the client and then filter them, so if BADGE_C is very large, this may not work well either, in which case you may have to push reqCardNos to the prowatchContext database in a temporary table and then do a join.

Try this:

var CardNoList = from BC in prowatchContext.BADGE_C 
                                              join lr in listReq on BC.CARDNO equals lr.CardNo where BC.STAT_COD != 'A'
                                              select BC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM