efcore icon indicating copy to clipboard operation
efcore copied to clipboard

FilterQuery ignored for DbSet<T>.Find

Open EdwinSaenz opened this issue 9 years ago • 2 comments

I set up a FilterQuery for a DbSet<Person> for when the person.DeletedEventId is not null to ignore people that have been deleted.

It works as expected when I use context.People.FirstOrDefault(p => p.PersonId == personId) but when I use context.People.Find(personId) it returns the entity.

Is this by design?

Steps to reproduce

[Fact]
public async Task WillNotFindEntitiesWithDeletedEventId()
{
    using (var context = InMemoryDb.CreateDbContext())
    {
        //arrange
        var deletedEvent = new Event();
        await context.Events.AddAsync(deletedEvent);
        var entity = new Person
        {
            DeletedEventId = deletedEvent.EventId
        };

        await context.People.AddAsync(entity);
        await context.SaveChangesAsync();

        //act
        // var actual = context.People.FirstOrDefault(p => p.PersonId == entity.PersonId);
        var actual = context.People.Find(entity.PersonId);
                
        //assert
        Assert.Null(actual);
    }
}
public class MyDbContext : IdentityDbContext<MyUser>
{
    public MyDbContext(DbContextOptions<MyDbContext> options)
        : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        FilterOutEntitiesWithDeletedEventId(builder);
    }

    private void FilterOutEntitiesWithDeletedEventId(ModelBuilder builder)
    {
        foreach (var e in builder.Model.GetEntityTypes().Where(e => typeof(IEventEntity).IsAssignableFrom(e.ClrType)))
        {
            var entityParameter = Expression.Parameter(e.ClrType, "e");
            var deletedEventIdProperty = Expression.Property(entityParameter, nameof(IEventEntity.DeletedEventId));

            var filter = Expression.Lambda(
                Expression.Equal(
                    deletedEventIdProperty,
                    Expression.Constant(null, deletedEventIdProperty.Type)),
                entityParameter);

            builder.Entity(e.ClrType).HasQueryFilter(filter);
        }

        public DbSet<Person> People { get; set; }
    }
}
public class Person : IEventEntity
{
    [Key]
    public int PersonId { get; set; }

    public int? DeletedEventId { get; set; }

    public virtual Event DeletedEvent { get; set; }
}
public interface IEventEntity
{
    int? DeletedEventId { get; set; }
}
static class InMemoryDb
{
    public static MyDbContext CreateDbContext() => new MyDbContext(
        new DbContextOptionsBuilder<MyDbContext>()
        .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
        .Options);
}

Further technical details

EF Core version: 2.0 Database Provider: InMemoryDatabase Operating system: Windows IDE: VS Code

EdwinSaenz avatar Aug 14 '17 19:08 EdwinSaenz

@EdwinSaenz Thanks for filing this issue. We had discussed this in the past and also re-assessed today and we are going to keep the current behavior. It's certainly not an easy choice, but it stems from this:

  • Query filters only apply to queries against the database. Once an entity is tracked by the state manager it is always accessible regardless of what filters are being used. There are several reasons for this, one of which is preserving filter semantics when they are applied in memory as opposed to in SQL.
  • Find sometimes runs a query, but only if the entity was not found in the state manager. This means that if a query filter is applied, then the behavior of Find can be confusing--sometimes it will return an entity, sometimes it won't depending on whether that entity has been cached in the state manager or not.

If it is important that a query filter be used to find an entity by ID, then running a FirstOrDefault query will ensure that the query is always run on the server and hence the always has consistent filter semantics.

ajcvickers avatar Aug 16 '17 20:08 ajcvickers

While running fresh unit tests against a newly designed EfCore Model, I myself could not figure out why my soft delete filter was not working with the context it was deleted on. Once I used methods other than Find() it worked as expected. I am thankful for this thread, otherwise I would have felt a lack of determinism with other potential query differences and would have written a lot more test cases than initially planned for.

I have no problem using calls like FirstOrDefault(), but when managing applications with a SLOC count of 200K, my concern will be assuring nobody uses the Find() method. It is a risk because the fluent API call along with Visual Studio auto-complete, make selecting it that much easier.

Using dependency injection to obtain a scoped DbContext means that another unrelated module could perform a Find() on that context where entities were previously deleted and end up processing those entities when it shouldn't be.

Just a little more food for thought.

I love the work you all do and I am thankful that EF was migrated to EfCore

jtbrower avatar Jan 23 '18 19:01 jtbrower