2015-11-24 179 views
0

我有我撰写这从一些选项的查询,这样查询组成了LINQ实体框架

string q1 ="SELEC * from MyTable"; 
string q2 =string .Empty; 

if(options1) 
q2+=" Condition_1 "; 
if(options2) 
q2+=" Condition_2"; 
if(!String.IsNullOrEmpty(q2)) 
q1+=" WHERE"+q2; 

cmd.Execute(... 

我该怎么做,对LINQ了在短短的一个尝试实体框架-6?

+0

你可以用三元运算符来检查条件,比如'from myTable where Options1? FieldtoCompare:-1等于Options1? “Condition_1”:0和Options2? FieldtoCompare:-1等于Options2? “Condition_2”:0' – Nilesh

+0

@Nilesh但有时候这个作品有多个表格,我在多个表格上有一些大的作品,只有当选项需要时才需要表格。 – saimmm0710

回答

0

你可以做到这一点通过与IQueryable的工作。 这个例子可以帮助你:

//Define your query without executing it.     
IQueryable<YourEntityType> query= (from s in Context.MyTable select s); 

if(options1) 
//Add a where clause to your IQueryable 
    query= query.Where(p=> p.SomeProperty == "Something"); 

if(options2) 
//Add another where clause to your IQueryable 
query= query.Where(p=> p.SomeProperty == "Something else"); 

//Executes the query depending your options. 
var Result = query.ToList(); 
+0

你的意思是,我可以编写linq而无需运行查询,毕竟,我将通过调用ToList或...运行一个且只有一个链接查询,谢谢 – saimmm0710

+0

是的,查询不会运行,直到你调用.toList(),.AsEnumerable()或其他任何检索你的行。 –

0

是的,你可以。你可以链接几个.Where操作。所以,你可以写SMT像

var set = MySet; 
    if (cond_1) { 
     set = set.Where(a=>...); 
    } 
    if (cond_2) { 
     set = set.Where(a=>...); 
    } 
    set.ToList()