1 Replies - 11628 Views - Last Post: 04 September 2012 - 10:56 AM

#1 kstr  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 60
  • Joined: 19-October 09

Soft delete with entity framework 4.1

Posted 18 May 2012 - 03:15 AM

I am trying to implement a soft delete using Entity Framework 4.1: (code is in vb.net but i know c# as well)

    Public Overrides Function SaveChanges() As Integer

        ' Get all Added/Deleted/Modified entities (not Unmodified or Detached)
        For Each ent As DbEntityEntry In Me.ChangeTracker.Entries().Where(Function(p) p.State = System.Data.EntityState.Added OrElse p.State = System.Data.EntityState.Deleted OrElse p.State = System.Data.EntityState.Modified)
            
            If ent.State = EntityState.Deleted AndAlso ent.OriginalValues.PropertyNames.Contains("IsDeleted") Then
                ent.State = EntityState.Modified
                ent.Property("IsDeleted").CurrentValue = True
            End If
            If ent.State = EntityState.Added AndAlso ent.CurrentValues.PropertyNames.Contains("IsDeleted") Then
                ent.Property("IsDeleted").CurrentValue = False
            End If
        Next
              Return MyBase.SaveChanges()
    End Function




When working with one-to-many relationships, i get the following error at the mybase.savechanges():

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types.

The innerexeption is this:
{"A relationship from the 'DepartementCustomer' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'Customer' must also in the 'Deleted' state."}


What am i missing?

Is This A Good Question/Topic? 0
  • +

Replies To: Soft delete with entity framework 4.1

#2 MKunstman  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 193
  • Joined: 26-October 09

Re: Soft delete with entity framework 4.1

Posted 04 September 2012 - 10:56 AM

Pretty sure you have to grab the customer (as indicated by the message) and remove that instance of the customer as well. You are basically deleting one column from a junction table but not the subsequent column...so if you're junction table is:

Department/Customer...you are removing the department and leaving the customer...but the customer has to have a department and thus, this save errors out. That instance needs both key values else both key values need to be handled....

So....You have to get the entity dept and entity customer that you need for this delete and remove the relationship from both sides...not just one.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1