views:

35

answers:

3

How can i make my own delete method to prevent that the data really gets deleted? i want to set a datetime field when it gets deleted insted of a normal delete.

i read about overriding the submitchanges function, but i don't get it to work

thanks

A: 

If you won't find out how to override the delete function, you can create an ON DELETE trigger for every table in database, that does not delete, but sets datetime field.

Draco Ater
i want to handle this all in my Data Acces Layer
k0ni
+2  A: 

Handle SavingChanges, go through the deleted items in the context, change their state to modified, and modify the field in question.

Craig Stuntz
Ok, but how can i set the entity to modified?the objectstateentry.state is readonlyi got this so far:else if (entry.State == System.Data.EntityState.Deleted) { MyClass Ref = MyClass entry.Entity; Ref.SysDeleted = DateTime.Now; Ref.SysDeletedBy = Username; }
k0ni
With [Context.ObjectStateManager.ChangeObjectState](http://msdn.microsoft.com/en-us/library/system.data.objects.objectstatemanager.changeobjectstate.aspx)
Craig Stuntz
Thanks, but why the hell don't i have this method?'System.Data.Objects.ObjectStateManager' does not contain a definition for 'ChangeObjectState'
k0ni
You may not be using EF 4.
Craig Stuntz
so, how to make it then? I can't use EF 4 yet..
k0ni
I'm not sure; I've never tried this in 3.5. Can you assign `EntityState`?
Craig Stuntz
+1  A: 

I wrote an interface IRequiredColumns with the properties CreatedOn, ModifiedOn and DeletedOn which every entity implements. Then I created this partial class for the context:

Partial Public Class Context
Public Overrides Function SaveChanges(ByVal options As System.Data.Objects.SaveOptions) As Integer
    For Each entry As ObjectStateEntry In ObjectStateManager.GetObjectStateEntries(EntityState.Added Or EntityState.Modified Or EntityState.Deleted)
        If TypeOf (entry.Entity) Is IRequiredColumns Then
            Dim entity As IRequiredColumns = CType(entry.Entity, IRequiredColumns)

            Select Case entry.State
                Case EntityState.Added
                    entity.CreatedOn = Now
                Case EntityState.Modified
                    entity.ModifiedOn = Now
                Case EntityState.Deleted
                    entry.ChangeState(EntityState.Modified)
                    entity.DeletedOn = Now                        
            End Select
        End If
    Next

    Return MyBase.SaveChanges(options)
End Function
End Class

This works great for me!

BrezelBob