我需要写一个Linq查询,其条件如下:
INNER JOIN
LEFT JOIN
。
bool ifexists = db.Users.Any(u => u.id== 1);
IQueryable<modelname> query;
if(ifexists == true)
{
query=my inner join linq;
query = from s in query select s;
return query.ToList();
}
else
{
query=my left join linq;
query = from s in query select s;
return query.ToList();
}
现在我怎么能写这个Linq?有没有办法在单Linq
语句中编写这个linq - 我不想写两次linq?
答案 0 :(得分:3)
在对数据库进行评估之前,您可以有条件地在IQueryable
上进行撰写 - 这将允许您至少部分地干掉分支的不同分支上的常见操作:
var query = db.SomeTable
.AsQueryable() // Not needed if `db.SomeTable` is already a Queryable
.Where(x => ** common predicates on x ** ));
// NB : Do not materialize here!
if(exists) // Don't need == true
{
query = query
.Where(x => ** branch 1 predicates **));
}
else
{
query = query
.Where(x => ** branch 2 predicates **);
}
return query
.Select(q => ** common fields to project **)
.OrderBy(q => ** common ordering **)
.ToList(); // Materialize right at the end
答案 1 :(得分:1)
你想要那样吗?
bool ifexists = db.Users.Any(u => u.id== 1);
var query=ifexists==true ? (my inner join linq) : (my left join linq);
return query.ToList();
答案 2 :(得分:0)
First create object of of database Context named **Objcontext**
now hold the variable in var the query would be like following
var Result = from a in Objcontext.tbl1 where !Objcontext.tbl2.Any(m=>(m.sid==a.aid)&&(m.mid==80))
select a;
If data is exists in the databse it will cheack using !Objcontext
I hope it will helpfull