views:

42

answers:

2

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

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

Craig Stuntz
+2  A: 

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

Equiso
And if the entity didn't exist when we tried to delete it, would it simply ignore it? Say another user deleted it before we got to it? Nice answer btw!
Dr. Zim
see edited.....
Equiso
See http://blogs.msdn.com/b/alexj/archive/2009/06/19/tip-26-how-to-avoid-database-queries-using-stub-entities.aspx for a list of 'stub entity' operations
Hightechrider