2

I'm running into the following problem:

In this project it is mandatory that the registries should not be physically (from the database) deleted, so I create a bool property named deleted on each class that represents a table on the database.

In a delete case, the property will become true and need to be only accessible, in any case, by SQL Queries inside the Database.

I made the repositories and etc to always return the IQueryables with a query.where(x => !x.Deleted), but how can I do this on the Collections that are 'lazy loaded' by EF?

For example, when I get a Person and it has a ICollection, it always comes populated with all objects linked to that Person, I always have to filter the deleted ones manually.

Is there a way to tell EF that in every Lazy Loading it should use a custom where clause?

1 Answer 1

3

You can filter out the deleted entities while mapping the DbSet itself by overriding OnModelCreating.

Example:

public class MyContext : DbContext
{
    public virtual IDbSet<Company> Companies { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Company>()
            .Map(m => m.Requires("IsDeleted").HasValue(false))
            .Ignore(m => m.IsDeleted);
    }
}

This will set a default value of false for the IsDeleted property and filters out records where IsDeleted is true.

More info: https://putshello.wordpress.com/2014/08/20/entity-framework-soft-deletes-are-easy/

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

1 Comment

Holy Moly, that works! Probably I was searching for the wrong keywords, I never though of 'soft delete' term.

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.