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 instead of a normal delete.

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

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

Ok, but how can i set the entity to modified? the objectstateentry.state is readonly i got this so far: else if (entry.State == System.Data.EntityState.Deleted) { MyClass Ref = MyClass entry.Entity; Ref.SysDeleted = DateTime.Now; Ref.SysDeletedBy = Username; }
Thanks, but why the hell don't i have this method? 'System.Data.Objects.ObjectStateManager' does not contain a definition for 'ChangeObjectState'
I'm not sure; I've never tried this in 3.5. Can you assign EntityState?
1

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!

Comments

0

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.

1 Comment

i want to handle this all in my Data Acces Layer

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.