Reputation: 1008
I need to write a Linq query where the condition like this:
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();
}
Now how I can write this Linq? Is there any way to write this linq in a single Linq
statement - I don't want to write the linq twice?
Upvotes: 2
Views: 769
Reputation: 35
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
Upvotes: 0
Reputation: 107317
You can conditionally compose on an IQueryable
before evaluating it against the database - this will allow you to at least partially DRY up the common actions on the different legs of your branching:
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
Upvotes: 3
Reputation: 21
You Want like That?
bool ifexists = db.Users.Any(u => u.id== 1);
var query=ifexists==true ? (my inner join linq) : (my left join linq);
return query.ToList();
Upvotes: 1