0

I am receiviing this error when I try to delete rows using entity framework. Really do not understand why!

The object cannot be deleted because it was not found in the ObjectStateManager.

   public void Delete(int ticketID)
            {

                Modules.Entity.gmEntities context = new Modules.Entity.gmEntities();

                var ticketitem = context.xticketitem.Select(p => p.TicketID == ticketID);

                ticketitem.ToList().ForEach(r => context.DeleteObject(r));

                context.SaveChanges();

            }
mko
  • 6,638
  • 12
  • 67
  • 118
  • Have a look at [The object cannot be deleted because it was not found in the ObjectStateManager](http://stackoverflow.com/questions/7791149/the-object-cannot-be-deleted-because-it-was-not-found-in-the-objectstatemanager) – huMpty duMpty Jul 15 '13 at 14:26

1 Answers1

1

By the call of context.xticketitem.Select(p => p.TicketID == ticketID); you will get a list of booleans that do not exist in context.

I think you should do something like this:

var ticketitem = context.xticketitem.Where(p => p.TicketID == ticketID);
ticketItem.ToList().ForEach(r => context.xticketitem.DeleteObject(r));
context.SaveChanges();

EDIT: I've moved .ToList() on the next line to make differences between our snippets more evident. Let's try revise it step by step:

  1. When you call var ticketitem = context.xticketitem.Select(p => p.TicketID == ticketID);

    You are creating query that will go by all xticketitems and return whether each item's TicketID equals ticketID variable passed as an argument to your Delete method. Result of this query is IEnumerable<bool>.

    My code returns IEnumerable<xticketitem>. It's main difference.

  2. When you call context.DeleteObject(r) your r variable is bool. and you are calling DeleteObject method on context. That mathod accepts parameter of type object (that's why you don't get error at compile time).

    I'm calling DeleteObject on xticketitem ObjectSet that accepts strogly-typed parameter of xticketitem type.

Oleksii Aza
  • 5,368
  • 28
  • 35