简体   繁体   中英

Custom where clause extension with default values EF Core 5.0.3

I am adding this on every query and I can't help but think there is a way that I could either do a custom where extension to have it their as default on my queries? Or am I over-thinking this?

I am talking about isActive and isDeleted which is for my soft delete columns.

I am using EF Core 5.0.3 if makes a difference, to what is avail to me I no it's only one line but I feel that allot of the repetitive code code be cut down. Or at least a cleaner way to enforce it? Its on every class that I will be querying.

public async Task<IActionResult> ClubRoles() {
    return View(await _context.ClubUsers.Where(w => w.isActive == true && w.isDeleted == false).ToListAsync();    
}

Easy enough with global query filters: https://docs.microsoft.com/en-us/ef/core/querying/filters

Your case is textbook usage

modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted);

In case you want to ignore it

blogs = db.Blogs
    .Include(b => b.Posts)
    .IgnoreQueryFilters()
    .ToList();

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