I'm using Entity Framework 6.0 with SQL Server localdb, I tried using the Enumerable.Contains feature, but I found it very slow when we have a big list.
I researched and found that there is a recommendation to use sql statements for this case, as described in:Why is .Contains slow? Most efficient way to get multiple entities by primary key?.
Now I wonder why the following statement is so slow, taking more than 180 seconds to run the "ToList ()"?
using (var context = new MyDbContext())
{
Random rand = new Random();
var ids = new List<int>();
for (int i = 0; i < 20000; i++)
ids.Add(rand.Next(550000));
Stopwatch watch = new Stopwatch();
watch.Start();
var values = new StringBuilder();
values.AppendFormat("{0}", ids[0]);
for (int i = 1; i < ids.Count; i++)
values.AppendFormat(", {0}", ids[i]);
var sql = string.Format(
"SELECT * FROM [MyDb].[dbo].[MyEntities] WHERE NOT [ID] IN ({0})",
values);
var result = context.Set<MyEntity>().SqlQuery(sql).ToList();
watch.Stop();
var msec = watch.ElapsedMilliseconds;
}
Note that the statement is similar to the link test3 above, except that we included the term "NOT".
Sorry my bad English^^.