【问题标题】:Sequence contains more than one element when using Contains in LINQ query在 LINQ 查询中使用包含时,序列包含多个元素
【发布时间】:2016-01-25 17:09:11
【问题描述】:

以下代码抛出 InvalidOperationException:序列包含多个元素。无论我是否有 Include 语句,都会发生错误。

long[] customerIDs; //Method parameter. Has valid values


var results = from x in DB.CycleCounts
              //.Include(y => y.CustomerInventoryItem)
              select x;

if (customerIDs != null && customerIDs.Length > 0)
{
    results = from x in results
              where customerIDs.Contains(x.CustomerInventoryItem.CustomerID)
              select x;

}

var cycleCounts = await results.ToListAsync(); //throws InvalidOperationException

我正在使用 ASP5 RC1 (Core) 和 Entity Framework 7

【问题讨论】:

  • 我猜你正试图在cycleCounts 中存储多个列表,其中cycleCounts 是一维的。是否可以调试这一行并检查输出是否正确?
  • 代码示例是否正确?您在 if 块中访问 c​​ycleCounts,但随后声明它。您的意思是“结果 = 来自结果中的 x...”?
  • 对不起,我在粘贴代码后重命名了一些东西。我现在修好了,谢谢你抓住它。
  • 您是否尝试在customerIDs[] 中返回任何customerId 的结果?
  • 是的,customerIDs[] 是一个过滤器。如果 customerIDs 有一个值,我只想要循环计数谁的客户 ID 在数组中。我尝试使用 Any() 而不是 Contains() 但它抛出了相同的异常。

标签: c# entity-framework linq-to-sql ef-code-first asp.net-core


【解决方案1】:

我不确定您的模型看起来如何,但我认为它们看起来如下所示(CycleCounts 和 CustomerInventoryItems 之间的关系正如我所期望的那样多对一):

型号:

[Table("CustomerInventorys")]
public class CustomerInventory
{
    public long ID { get; set; }
    public long CustomerID { get; set; }

    public virtual ICollection<CycleCount> CycleCounts { get; set; }
}

[Table("CycleCounts")]
public class CycleCount
{
    public long ID { get; set; }

    public long CustomerInventoryItemID { get; set; }
    public virtual CustomerInventory CustomerInventoryItem  { get; set; }
}

所以如果我的建议是正确的,我建议你重写你的代码:

    IQueryable<CycleCount> results = null;

    if (customerIDs != null && customerIDs.Length > 0)
    {
        results = from invent in DB.CustomerInventorys
                  where customerIDs.Contains(invent.CustomerID)
                  join cycle in DB.CycleCounts on invent.ID equals cycle.CustomerInventoryItemID                          
                  select cycle;    
    }
    else
        results = DB.CycleCounts;

    var cycleCounts = await results.ToListAsync();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 2015-01-21
    • 2014-03-09
    • 2013-02-07
    • 2014-01-01
    • 2016-10-19
    • 1970-01-01
    相关资源
    最近更新 更多