1

I was deleting an Entity based on it's primary key, then I made my repository generic. Here's my current delete method:

public void Del(E entity) // where E : EntityObject on the class
{   if( entity != null)
        DC.DeleteObject( entity);
    return; 
}

It's running in a MVC 2 web application. So, the users send up primary key values from an Entity to delete, I create a new entity then ship it to the Delete method. This would extract the primary key and delete the item using a Where() clause. It just seems silly to query the database first.

1
  • did you test it? if it is ok no matter but else using Where() clause doesn't add any extra order for deleting item it should search for item. Oct 28, 2010 at 16:04

2 Answers 2

4

On EF 4 you don't need to query the object to delete (or update) but you need to set the primary key and attach it to your context. Your method would look like this:

public void Del(E entity) // where E : EntityObject on the class
{   
    if( entity != null)
    {
        DC.Attach(entity);
        DC.DeleteObject( entity);
        DC.SaveChanges();
    }
}

Edit:

The DeleteObject method can be called on objects that are already deleted. http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.deleteobject.aspx

2
1

You don't need to retrieve it, but you do need to attach it to the context if you don't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.