简体   繁体   中英

Create pre filter layer in DbSet

I want to protect my entities using a Field called Deleted to don't allow client really delete any entity. If he tries delete, the only thing is that entity.Deleted = true;

The problem is that everywhere I don't want to include deleted Entities I'll need to use

db.Entities.Where(e => e.Deleted == false).WhateverMethod();

I know I can use a method like this inside my Controller

private IQueryable<Entity> GetNotDeletedEntity() {
        return db.Entities.Where(e => e.Deleted == false);
}

And change every db.Entities.WhateverMethod() for GetNotDeletedEntity().WhateverMethod() , but I seems weird for me.

One note is that GetNotDeletedEntity() returns IQueryable, and db.Entities returns DbSet. This incongruency may be a problem in the future.

I think there's a way to extend DbSet to work like this

db.Entities // include all entities

db.NotDeletedEntities // include only entities e.Deleted == false

Any advice about how to DRY .Where(e => e.Deleted == false) would be great.

Seems like this guy was trying to accomplish something very similar. Take a look at Jon Skeet's explanation here: extension for DbSet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM