I want to query data from database by multiple primary keys at once by using Linq. However, I store my primary keys in Dictionary<int, string>
My dictionary
private Dictionary<int,string> dict = new Dictionary<int, string>
{
{1, "Value 1"},
{2, "Value 2"},
{3, "Value 3"},
{4, "Value 4"},
{5, "Value 5"},
{6, "Value 6"}
};
In Raw SQL
SELECT * FROM Article WHERE ArticleId IN (1,2,3,4,5,6);
I have tried in Linq
var article = new NewsEntities().Articles;
var mainArticles = article.Where(a => dict.ContainsKey(a.ArticleId));
foreach (var mainArticle in mainArticles)
{
Console.WriteLine(mainArticle.ArticleId);
}
The error I have got
System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean ContainsKey(Int32)' method, and this method cannot be translated into a store expression.'
AsEnumerable
:article.AsEnumerable().Where(a => dict.ContainsKey(a.ArticleId));
.Console.WriteLine
?ToList
:article.ToList().Where(a => dict.Contains(a.ArticleId));
. No need to useContainsKey
there.