I have the following linq queries:
Var q1 = (from t1 in context.Table1
where column = value
select t1).FirstOrDefault();
Var q2 = (from t2 in context.Table2
where column = value
select t2).FirstOrDefault();
As far as I understand, the above linq statements will call the database two times to get the table data but I want to write the linq query in such a way to get both the tables data in a single database call. How can I achieve this?
You can achieve this by selecting to anonymous type:
Var q = (from t1 in context.Table1
where t1.column == value
select t1
)
.Select(t1 => new {
t1 = t1,
t2 = context.Table2
.FirstOrDefault(t2 => t2.column == value);
})
.FirstOrDefault();
var t1 = q.t1;
var t2 = q.t2;
This way it will make one query from this all. I simplified a bit the query part to obtain t2 item, but there is not obstacle to use the one you wrote.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With