sequence包含多个元素

时间:2009-10-12 20:19:23

标签: database entity-framework

在尝试填充我的促销表对象时,我收到以下错误“序列包含多个元素”。我知道我收到此错误,因为我的查询返回多个值,因为它应该。任何人都可以指出我正确的方向,除了循环之外如何删除多个记录(如果可能的话,使用EF)。

主要过程:

    TBLPROMOTIONCOLLECTION promotionCollectionInfo = null;
using (webStoreEntities webStoreContext = new webStoreEntities())
{
  promotionCollectionInfo = WebStoreDelegates.selectPromotionCollection.Invoke    (webStoreContext).ByPromoID(promotionId).ToList().SingleOrDefault();

  if (promotionCollectionInfo != null)
  {
     webStoreContext.DeleteObject(promotionCollectionInfo);
     webStoreContext.SaveChanges();
  }
}

selectPromotionCollection Delegate:

        public static Func<webStoreEntities, IQueryable<TBLPROMOTIONCOLLECTION>> selectPromotionCollection =
    CompiledQuery.Compile<webStoreEntities, IQueryable<TBLPROMOTIONCOLLECTION>>(
        (promotion) => from c in promotion.TBLPROMOTIONCOLLECTION
                       select c);

ByPromoID过滤器:

        public static IQueryable<TBLPROMOTIONCOLLECTION> ByPromoID(this IQueryable<TBLPROMOTIONCOLLECTION> qry, int promotionID)
    {
        //Return the filtered IQueryable object
        return from c in qry
               where c.PROMOTION_ID == promotionID
               select c;
    }

FirstorDefault不能解决我的问题,因为我期待倍数。 任何帮助,将不胜感激。

谢谢,比利

1 个答案:

答案 0 :(得分:1)

错误在这里:

.SingleOrDefault();

(主要过程的第3行)当IQueryable返回&gt;时抛出1个元素,你的ByPromoId。

一种解决方法是将代码更改为:

promotionCollectionInfo = WebStoreDelegates.selectPromotionCollection
    .Invoke(webStoreContext).ByPromoID(promotionId).ToList();

foreach (var pc in promotionCollectionInfo)
{
    webStoreContext.DeleteObject(pc);
}
webStoreContext.SaveChanges();
相关问题