1

I have these two tables

ExpiredAccount                    Account
--------------                    ---------------
ExpiredAccountID                  AccountID
AccountID (fk)                    AccountName
...                               ...

Basically, I want to return a list of ExpiredAccounts displaying the AccountName in the result.

I currently do this using

var expiredAccounts = (from x in ExpiredAccount
                       join m in Account on x.AccountID equals m.AccountID
                       select m.AccountName).ToList()

This works fine. However, this takes too long. There's not a lot of records in expiredAccounts (<200). The Account table on the otherhand has over 300,000 records.

Is there anyway I could speed up my query, or alternatively, another way to do this more efficiently with or without using LINQ?

4

2 回答 2

1

You can try using Contains method:

var expiredAccounts = (from m in Account where ExpiredAccount.Select(x => x.AccountId)
                                                             .Contains(m.AccountId)
                       select m.AccountName).ToList()

It should generate IN clause in SQL query that will be performed agains database.

于 2013-04-22T18:20:48.270 回答
1

Firstly, assuming you are using Entity Framework, you don't need to be using the join at all. You could simply do:

var expiredAccounts = (from x in ExpiredAccount
                       select x.Account.AccountName).ToList()

However, I don't think they will generate a different query plan on the database. But my guess is that you don't have an index on AccountID in the Account table (although that seems unlikely).

One thing you can do is use ToTraceString (for example: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/4a17b992-05ca-4e3b-9910-0018e7cc9c8c/) to get the SQL which is being run. Then you can open SQL Management Studio and run that with the execution plan option turned on and it will show you what the execution plan was and what indexes need to be added to make it better.

于 2013-04-22T18:27:31.933 回答