2

I am using code-first Entity Framework 6.0 and have implemented a soft delete solution based on https://putshello.wordpress.com/2014/08/20/entity-framework-soft-deletes-are-easy/. This works well and automatically ignores the records where IsDeleted is true. So my model builder has an entry similar to the following:

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

I now have a requirement to access the deleted records, but only in one section of the application. So I need to select the records where IsDeleted is true.

If I attempt to simply use:

    where company.IsDeleted = true

It will fail with the following message:

The specified type member 'IsDeleted' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

I have looked everywhere and there is plenty of information about Entity Framework Core 2.0, but nothing about EF6.1. Short of using SQL scripts with the old SqlClient, does anyone have any hints of how to access these records using linq to entities?

Scho
  • 351
  • 1
  • 2
  • 12
  • You are setting IsDeleted to be ignored in your mapping ```.Ignore(m => m.IsDeleted);```, I believe it will cause the issue you are getting. – Aderbal Farias Apr 01 '19 at 14:52
  • That's correct. This setting works as intended. I just need to switch it off for one section of the application. – Scho Apr 01 '19 at 15:02
  • 1
    I have faced that issue before and it was happening because of my mapping you can check this [link](https://stackoverflow.com/questions/11584660/the-specified-type-member-is-not-supported-in-linq-to-entities-only-initializer), it may help you – Aderbal Farias Apr 01 '19 at 15:16
  • 1
    There is no way to ignore fluent mapping once it's been established. All I can think of is to create another `DbContext` derived class w/o that fluent configuration. – Ivan Stoev Apr 01 '19 at 17:20
  • You are right @Ivan Stoev. – Scho Apr 01 '19 at 19:29

1 Answers1

4

In the end, the only way to easily resolve this was to implement EntityFramework.DynamicFilters from https://github.com/zzzprojects/EntityFramework.DynamicFilters. This is a great solution and provides the flexibility to switch off a filter dynamically.

protected override void OnModelCreating( DbModelBuilder modelBuilder )
{
    modelBuilder.Filter( "IsDeleted", ( ISoftDelete d ) => d.IsDeleted, false ));
}

You then add an interface:

internal interface ISoftDelete
{
    bool IsDeleted { get; set; }
}

Then, switch off (as required) the IsDeleted filter:

ctx.DisableFilter( "IsDeleted" );

Much easier!

Scho
  • 351
  • 1
  • 2
  • 12