Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select multiple objects using one linq query in entity framwork 6

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?

like image 924
seadrag0n Avatar asked May 15 '26 10:05

seadrag0n


1 Answers

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.

like image 139
mr100 Avatar answered May 18 '26 00:05

mr100



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!