在LINQ查询中使用Contains时,Sequence包含多个元素

时间:2016-01-25 17:09:12

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

以下代码抛出InvalidOperationException:Sequence包含多个元素。无论我是否包含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

1 个答案:

答案 0 :(得分:0)

我不确定如何看待你的模型,但我认为它们看起来像下面的东西(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();