简体   繁体   中英

Convert LINQ query to SQL query for better performance by using joins

I want to improve my query performance. When you take a look at my previous question, you will see my question. I asked you for modifying my LINQ query. Because I need really better performance.

But I decided to look at the equality of SQL for my LINQ query. As a result, How can I convert below LINQ to SQL with taking care of performance issues? Because I need to have a better performance, that's the reason; it is more essential than before. Someone who is willing to answer this question has to focus on

  1. Better performance
  2. SQL equality.
data.ForEach(x =>
{
    foreach (var item in x.SalesItems)
    {
        if (orderItemType.Any(y => y == item.Value))
        {
            var x = DbContext.Set<Customer>()
                            .Include(q => q.Table1)
                            .Include(q => q.Table2)
                            .FirstOrDefault(q => q.Id == item.Key);
            if (x != null)
            {
                var y = DbContext.Set<Order>()
                                .Include(q => q.OrderDetail)
                                .FirstOrDefault(q => q.PNRId == x.PNRID);

                x.OrderNo = x.OrderNumber;
                x.CustomerName = x.Table1.Name + " " + x.Table1.Surname;
                x.OrderProviderName = y.OrderDetail.Id;
                x.CityCode = y.OriginCityCode + " - " + y.DestinationCityCode;
            }
        }
    }
});```

I don't answer directly to your question but a TIP to optimize query under SQL Server is to use the analyze "Missing Index", a good INDEX can run your query twice faster.

Take the SQL String and copy it into SQL Server Management Studio, run you query with the icon "Display Estimated Execution Plan"

图标显示预计执行计划

After this, if you query needs to create an INDEX, you see in green something like that: 缺失索引

Click on the menu "Missing Index Details" and execute the Index with a new name undex

You'll see a better performance and it's a TIP to check everytime when you exeuctes queries in your project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM