Curious problem getting an IQueryable<int> collection to work in a foreach loop
I'm building a repository method (Entity Framework) to take in a collection of ids supplied by checkboxes in a form as part of a CMS, and updating a lookup table (entity set) that relates topics to publications.
I have this method in a respository:
public void AttachToTopics(int pubId, IQueryable<int> topicsForAssociation, IQueryable<int> topicsSubset, int primaryTopicId)
{
// EVERYTHING IS FINE IF I INSERT A MANUAL COLLECTION OF int LIKE THIS:
// var priorAssociatedTopics = new[] { 2 }.AsQueryable(); //
// BUT WHAT I REALLY NEED TO WORK IS THIS:
IQueryable<int> priorAssociatedTopics = ListTopicIdsForPublication(pubId);
var priorAssociatedTopicsToExamine = priorAssociatedTopics.Intersect(topicsSubset);
var topicsToAdd =
associatedTopics.Intersect(topicsSubset).Except(priorAssociatedTopicsToExamine);
foreach (var topicToAdd in topicsToAdd)
AttachToTopic(pubId, topicToAdd);
foreach (var topicToRemove in priorAssociatedTopicsToExamine.Except(associatedTopics))
DetachFromTopic(pubId, topicToRemove);
}
AttachToTopics chokes on the first foreach loop, yielding this error message:
This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code.
But the problem is really with the first line: the repository method called on that line provides the appropriately typed collection into priorAssociatedTopics, and Intellisense has no problem with explicitly typing it as IQueryable (normally, I'd use var), and the debugger shows that this variable holds a collection of integers.
public IQueryable<int> ListTopicIdsForPublication(int pubId)
{
var topics = from x in DataContext.TopicPublications where x.PublicationId == pubId select x;
return topics.Select(t => t.Id);
}
However, back in attachToTopics, my topicsToAdd collection doesn't get populated, and its Results View in debug ho开发者_StackOverflowlds the aforementioned error message.
Curiously, if I switch in a manually generated IQueryable collection of ints for priorAssociatedTopics (see comment in code, above) the foreach loop works fine. So I beleive I need to find some other way to get priorAssociatedTopics populated with ints from a method call in my repository.
Any clue out there?
Is there any reason that ListTopicIdsForPublication
can't return an IEnumerable<int>
or an IList<int>
in this case? If so, adding a .ToList()
at the end of topics.Select(t => t.ID)
will ensure that the query gets run at that point.
It's not so much that it's IQueryable<int>
that's causing the problem, but rather IQueryable<int>
from DataContext.TopicPublications
. It looks like it's losing it's contextual data information and that's why you're getting the exception.
精彩评论