title: optimize query with lambra expression in entity framework
body: <p>I have the following query, often have excution timeout errors, have any ideas for optimization.
  Thank you!</p>
  
  <pre><code>queryResult = db.Products
                              .Where(x =&gt; !x.product_is_deleted)
                              .Where(x =&gt; x.product_name.Contains(keyword) || x.product_barcode.Contains(keyword) || x.ProductType.pro_type_name.Contains(keyword) || x.ProductType.pro_type_name.Contains(keyword))
                              .Select(x =&gt; new ProductView
                              {
                                  product_id = x.product_id,
                                  product_barcode = x.product_barcode,
                                  product_name = x.product_name,
                                  product_unit = x.product_unit,
                                  product_size = x.product_size,
                                  product_weight = x.product_weight,
                                  product_type_id = x.product_type_id,
                                  product_inventory = shelf == 0 ? (x.ImportProductDetails.Where(y =&gt; y.imp_pro_detail_product_id == x.product_id &amp;&amp; y.ImportProduct.import_pro_warehouse_id == warehouse_id ).Select(y =&gt; y.imp_pro_detail_inventory).DefaultIfEmpty(0).Sum()) : (x.ImportProductDetails.Where(y =&gt; y.imp_pro_detail_product_id == x.product_id &amp;&amp; y.ImportProduct.import_pro_warehouse_id == warehouse_id  &amp;&amp; y.imp_pro_detail_shelf_id == shelf).Select(y =&gt; y.imp_pro_detail_inventory).DefaultIfEmpty(0).Sum()),
                                  product_opening_stock = x.product_opening_stock,
                                  product_type_name = x.ProductType.pro_type_name,
                                  product_price = x.ProductPrices.Where(y =&gt; !y.proprice_is_deleted).Where(y =&gt; y.proprice_applied_datetime &lt;= DateTime.Now).OrderByDescending(y =&gt; y.proprice_applied_datetime).Select(y =&gt; y.proprice_price).FirstOrDefault(),
                                  product_discount_type = x.ProductDiscounts.Where(y =&gt; !y.pro_discount_is_deleted &amp;&amp; y.pro_discount_start_datetime &lt;= datetimeNow &amp;&amp; y.pro_discount_end_datetime &gt;= datetimeNow).OrderByDescending(y =&gt; y.pro_discount_id).Select(y =&gt; y.pro_discount_type).FirstOrDefault(),
                                  product_discount_value = x.ProductDiscounts.Where(y =&gt; !y.pro_discount_is_deleted &amp;&amp; y.pro_discount_start_datetime &lt;= datetimeNow &amp;&amp; y.pro_discount_end_datetime &gt;= datetimeNow).OrderByDescending(y =&gt; y.pro_discount_id).Select(y =&gt; y.pro_discount_value).FirstOrDefault()
                                  //product_norm_name = x.ProductionNorms.Where(y =&gt; y.pro_norm_name == x.product_id &amp;&amp; y.pro_norm_is_applied == true).Select(y =&gt; y.pro_norm_id).FirstOrDefault()
                              });
  </code></pre>