Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override delete function in entity framework

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

like image 259
k0ni Avatar asked Sep 16 '26 19:09

k0ni


2 Answers

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

like image 116
Craig Stuntz Avatar answered Sep 19 '26 17:09

Craig Stuntz


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!

like image 36
FabianAlbrecht Avatar answered Sep 19 '26 18:09

FabianAlbrecht



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!