So i'm trying to implement a soft delete feature, and I have a DeletedAt field in almost all of my tables. My problem now is since this feature is not native to Web API, I would have to put a where clause of DeletedAt == null in all of my queries. My question would be, is there a way to put this where clause globally either in Web API or maybe if it's also possible from SQL Server?
-
Are you using EF?Mihail Stancescu– Mihail Stancescu2017-11-25 08:00:11 +00:00Commented Nov 25, 2017 at 8:00
-
Yes I am using EF.Jed– Jed2017-11-26 06:29:41 +00:00Commented Nov 26, 2017 at 6:29
Add a comment
|
1 Answer
I hope you are using Entity Framework. You can add a global filter at OnModelCreating event by adding a discriminator like:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Foo>().Map(m => m.Requires("DeletedAt").HasValue(false));
modelBuilder.Entity<Bar>().Map(m => m.Requires("DeletedAt").HasValue(false));
}
OR
You can use this package: https://github.com/zzzprojects/EntityFramework.DynamicFilters
2 Comments
Jed
Yes I am using EF, will try that later.
Jed
Tried your answer. Do I need to update migrations or anything? Cause I get the following error:
Schema specified is not valid. Errors: error 2019: Member Mapping specified is not valid. The type 'Edm.DateTime[Nullable=True,DefaultValue=,Precision=]' of member 'DeletedAt' in type 'MyModel' is not compatible with 'SqlServer.bit[Nullable=True,DefaultValue=]' of member 'DeletedAt' in type 'CodeFirstDatabaseSchema.MyModel'.