views:

548

answers:

1

Hi everyone, 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

A: 

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();
Craig Stuntz
Kind of what i wanted to avoid. This loop can be rather long so deleting upwards of 100 to 200 records 1 at a time seems pretty draining compared to a single deletion of all those records. Just went ahead and mapped an sp to my entity table's cud mappings and formed my deletion sp to get rid of the multiples i wanted.Thansk for your quick response though.
Billy Logan
You said you wanted to get around the error. I got you around the error. If you actually have an entirely different question, could you ask it directly?
Craig Stuntz