Billy Logan
Billy Logan

Reputation: 2863

sequence contains more than one element

I receive the following error "sequence contains more than one element" when trying to populate my promotion table object. I know i recieve this error becuase my query returns multiple values as it should. Can anyone point me in the right direction as to how to delete multiple records besides looping(if possible with EF).

main proc:

    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 filter:

        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 doesn't fix my problem since i am expecting multiples. Any help would be appreciated.

Thanks, Billy

Upvotes: 1

Views: 6897

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126577

The bug is here:

.SingleOrDefault();

(3rd line of your main proc.) This throws when the IQueryable returns > 1 element, which your ByPromoId does.

One fix would be to change your code to:

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

foreach (var pc in promotionCollectionInfo)
{
    webStoreContext.DeleteObject(pc);
}
webStoreContext.SaveChanges();

Upvotes: 1

Related Questions