【问题标题】:Curious problem getting an IQueryable<int> collection to work in a foreach loop让 IQueryable<int> 集合在 foreach 循环中工作的奇怪问题
【发布时间】:2011-05-07 12:17:14
【问题描述】:

我正在构建一个存储库方法(实体框架),以接收由表单中的复选框提供的 id 集合作为 CMS 的一部分,并更新将主题与出版物相关联的查找表(实体集)。

我在存储库中有这个方法:

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 在第一个 foreach 循环中阻塞,产生以下错误消息:

This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code.

但问题实际上出在第一行:在该行上调用的存储库方法将适当类型的集合提供到priorAssociatedTopics 中,并且 Intellisense 将其显式键入为 IQueryable 没有问题(通常,我会使用 var),并且调试器显示此变量包含整数集合。

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);
}

但是,回到 attachToTopics 中,我的 topicsToAdd 集合没有被填充,并且它在调试中的结果视图包含上述错误消息。

奇怪的是,如果我为priorAssociatedTopics 切换手动生成的IQueryable 整数集合(参见上面代码中的注释),foreach 循环可以正常工作。所以我相信我需要找到一些其他方法来从我的存储库中的方法调用中获取使用整数填充的priorAssociatedTopics。

有什么线索吗?

【问题讨论】:

    标签: c# entity-framework iqueryable


    【解决方案1】:

    在这种情况下,ListTopicIdsForPublication 是否有任何原因无法返回 IEnumerable&lt;int&gt;IList&lt;int&gt;?如果是这样,在topics.Select(t =&gt; t.ID) 末尾添加.ToList() 将确保查询在该点运行。

    导致问题的不是IQueryable&lt;int&gt;,而是来自DataContext.TopicPublicationsIQueryable&lt;int&gt;。看起来它正在丢失它的上下文数据信息,这就是你得到异常的原因。

    【讨论】:

    • 就是这样! Ilist 似乎不起作用,因为我似乎无法转换回可查询(对吗?)。但是 IEnumerable 做到了。谢谢。
    • @ataddeini,我在不同的情况下看到了同样的异常......你有经验的眼睛能够查明我的问题吗? stackoverflow.com/questions/7787625/…
    猜你喜欢
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 2020-07-12
    相关资源
    最近更新 更多