简体   繁体   中英

Including values from external table in a LINQ statement

I want to write LINQ query for following SQL query:

    SELECT A.ID
    FROM TABLE_1 A, TABLE_2 B
    WHERE A.ID = B.ID
    AND B.STATEID IN (SELECT C.STATEID FROM STATE C WHERE C.REGIONID = 1)

For this I've managed to make following query:

    var var1 = (from a in db.table_1
                join b in db.table_2
                on a.Id equals b.Id
                where b.stateid = 
                select new
                {
                   a.Id
                }).ToList();)

Here how can I include all the StateIDs where RegionId is 1 to get the necessary output.

Your equivalent Linq query would be something:

var result = (from a in db.table_1
              from b in db.table_2 
               where a.Id == b.Id
               && db.State.Any(c=>c.REGIONID  == 1 && b.StateId == c.StateId) 
                select new
                {
                   a.Id
                }).ToList();

You can use Any :-

where db.States.Any(x => x.RegionId == 1 &&  x.StateId == b.StateId)
select...

You can try this..

var var1 = (from a in db.table_1
            join b in db.table_2
            on a.Id equals b.Id
            where db.State.Any(c=> c.RegionId == 1 && c.StateId == b.StateId)
            select new
            {
               a.Id
            }).ToList();)

Try this,

var var1 = (from a in db.table_1
                join b in db.table_2
                on a.Id equals b.Id
                where (db.State.Where(x => x.RegionId == 1).Select(x => 
                       x.StateId)).Contains(b.Id)
                select new
                {
                   a.Id
                }).ToList();)

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