LINQ subquery IN

不羁的心 提交于 2019-12-18 16:51:14

问题


I'm a newbie with the IQueryable, lambda expressions, and LINQ in general. I would like to put a subquery in a where clause like this :

Sample code :

SELECT * FROM CLIENT c WHERE c.ETAT IN (
 SELECT DDV_COLUMN_VAL FROM DATA_DICT_VAL
 WHERE TBI_TABLE_NAME = 'CLIENT' AND DD_COLUMN_NAME = 'STATUS'
           AND DDV_COLUMN_VAL_LANG_DSC_1 LIKE ('ac%'))

How do I translate this in LINQ ?


回答1:


var innerquery = from x in context.DataDictVal
                 where x.TbiTableName == myTableNameVariable
                    && x.DdColumnName == "Status"
                    && x.DdbColumnValLangDsc1.StartsWith("ac")
                 select x.DdvColumnVal;

var query = from c in context.Client
            where innerquery.Contains(c.Etat)
            select c;



回答2:


from c in db.Client
where (from d in db.DataDictVal 
       where d.TblTableName == "Client" 
         && d.DDColumnName == "Status"
         && dd.DdvColumnValLandDsc1.StartsWith("ac"))
       .Contains(c.Etat)
select c;



回答3:


If you are new to Linq, you absolutely need two essential tools. The first is a tool that converts most T-SQL statements to Linq called Linqer (http://www.sqltolinq.com/). This should take care of the query in your question. The other tool is LinqPad (http://www.linqpad.net/). This will help you learn Linq as you practice with queries.

I often use Linqer to convert a T-SQL query for me, and then use LinqPad to fine tune it.




回答4:


Same example with Linq method syntax:

var innerquery =  dbcontext.DataDictVal                  
                 .where(x=> x.TbiTableName == myTableNameVariable
                    && x.DdColumnName == "Status"
                    && x.DdbColumnValLangDsc1.StartsWith("ac"))
                 .select(x=>x.DdvColumnVal)

var query = dbcontext.Client
            .where( c=>innerquery.Contains(c.Etat))

Note:

Am providing this answer, because when i searched for the answer, i couldn’t find much answer which explains same concept in the method syntax.

So In future, It may be useful for the people, those who intestinally searched method syntax like me today. Thanks karthik



来源:https://stackoverflow.com/questions/3477918/linq-subquery-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!