Dynamic select in query with linq

dynamic-linq linq linq-to-sql

Question

I see Dynamic linq in below link: ScottGu

I want to use this method to select a dynamic query like this:

I have a complex select and this way not solve my problem, this is my select:

Select sUserName,sname, sFamily,sMobail,sid,sNumberSt,sActive,sPic,sDate from Student where {0} order by sid desc";

which {0} is a complex Condition:

sname like %somthing% and susername=N'something' and sid in (select sidfk from tablex where userteacher=N'name1')

and this condition is passed to method. I must say that: I don's know my condition,my condition specified with user search params.this condition that I say,Is only one example of what I want to do.

How can I do this?

1
1
12/8/2013 10:46:23 AM

Accepted Answer

Only way that solve my problem:

I send tow parameters instead of one,one for student and one for tablex:

var az = db.tablex.Where(p => p.userteacher== name1)
            .Select(p => p.sidfk).ToList();
        var query = db.Students.Where(textSearch).Where(s=>az.Contains(s.sid)).OrderByDescending(s => s.sid)
            .Select(s => new
            {
               s.sUserName,
                s.sname,
                s.sFamily,
                s.sMobail,
                s.sid,
                s.sNumberSt,
                s.sActive,
                s.sPic,
                s.sDate,
            });

wiche textSearch is :

sname like %somthing% and susername=N'something'

with dynamic linq

any better way is exist?

1
12/5/2013 5:47:07 AM

Popular Answer

Dynamic Linq usually use if in query you don't know what field will be use, so in your sample you use only params for conditions with field, so you don't ned dynamic linq

you can little optimize you query like this

var query = from student in db.Students
            join teacher in db.tablex on student.sid equals teacher.sidfk
            where student.sname.Contains('somthing') && 
                  susername=='something' &&
                  teacher.userteacher=='name1'
            orderby s.sid descending 
            select new
                {
                    s.sUserName,
                    s.sname,
                    s.sFamily,
                    s.sMobail,
                    s.sid,
                    s.sNumberSt,
                    s.sActive,
                    s.sPic,
                    s.sDate,
               };


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow