Reputation: 2844
I use Entity Framework 5 in an MVC application. I save a list of matches and before I do the actual update, I want to load all posted matches into the EF memory.
I have the following code (which works). _context is my EfDbContext:
public bool UpdateMatches(IEnumerable<Match> matchesToUpdate, int userID)
{
matchesToUpdate = matchesToUpdate as List<Match> ?? matchesToUpdate.ToList();
var matchIDs = matchesToUpdate.Select(m => m.ID).ToArray();
_context.Matches.Where(x => matchIDs.Contains(x.ID)).Load();
}
But what I actually want is something like this:
public bool UpdateMatches(IEnumerable<Match> matchesToUpdate, int userID)
{
_context.Matches.Where(m => matchesToUpdate.Any(x => x.ID == m.ID)).Load();
}
But I'm getting the error
"Unable to create a constant value of type 'Matches'. Only primitive types or enumeration types are supported in this context."
I also tried it with Contains, but no luck. What am I doing wrong?
Upvotes: 1
Views: 231
Reputation: 125630
Get list of ID
from your matchesToUpdate
collection and use Contains
instead of Any
:
public bool UpdateMatches(IEnumerable<Match> matchesToUpdate, int userID)
{
var ids = matchesToUpdate.Select(x => x.ID).ToList();
_context.Matches.Where(m => ids.Contains(m.ID)).Load();
}
It will result in IN
statement within generated SQL query.
Upvotes: 2