Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When overriding SaveChanges and removing the EF relationship is null

In my many-to-one relationship I am trying to delete one of the child objects and keep an audit trail in my overridden SaveChanges.

The file.Entity.Product is not null when doing an EntityState.Modified or EntityState.Added but when doing a .Deleted EF seems to be aggressively removing the relationship from the entity even before base.Savechanges() is called.

Is there any way to retrieve when Product this file was associated with in my SaveChanges override after I have called .Remove on the File (child)?

var files = from e in ChangeTracker.Entries<SavedFile>()
                    where e.State != EntityState.Unchanged
                    select e;
if (file.State == EntityState.Deleted)
            {
                var text = "File Deleted: " + file.Entity.FriendlyFileName;
                // file.Entity.Product is null
                var updatedProduct = new Update { Product = file.Entity.Product, UpdateDateTime = DateTime.Now, UpdateText = text, User = HttpContext.Current.Request.LogonUserIdentity.Name };
                Updates.Add(updatedProduct);
            }
like image 333
DTown Avatar asked Oct 19 '22 06:10

DTown


2 Answers

Just as you find the file in the ChangeTracker's entries, you can find its product, assuming that File has a foreign key association with Product, i.e. it has a ProductID property besides a Product navigation property:

if (file.State == EntityState.Deleted)
{
    var text = "File Deleted: " + file.Entity.FriendlyFileName;
    var productEntry = ChangeTracker.Entries<Product>()
                                    .FirstOrDefault(p => p.Entity.ID == file.ProductID);
    if (productEntry != null)
    {
        var updatedProduct = new Update { Product = productEntry.Entity, UpdateDateTime = DateTime.Now, UpdateText = text, User = HttpContext.Current.Request.LogonUserIdentity.Name };
        Updates.Add(updatedProduct);
    }
}

It's expected behavior that EF doesn't show deleted entities whenever entities are queries from the local cache (e.g. DbSet.Local). So it also has to break associations to prevent these entities from appearing in navigation properties. If you delete a file, EF won't display it in context.Files.Local, but neither will it be visible in a navigation property like product.Files (and neither will the other side of the association, file.Product).

like image 160
Gert Arnold Avatar answered Nov 15 '22 06:11

Gert Arnold


I think that there is no way to access the relation ship after deletion

but, why don't you use the soft delete, which is the best practice in my opinion, at any time you can return back the deleted record if was deleted mistakenly ( by marking IsDeleted = false, by the admin with authority)

hope this will help you

like image 45
Monah Avatar answered Nov 15 '22 05:11

Monah