mko
mko

Reputation: 7325

Error deleting rows in entity framework

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();

            }

Upvotes: 0

Views: 117

Answers (1)

Oleksii Aza
Oleksii Aza

Reputation: 5398

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.

Upvotes: 1

Related Questions