I'm using Entity Framework 6 with database first. In a current project I have some rows in the database that never should be fetched by Entity Framework. Let's say that I have this simplified model:
public partial class Customer
{
public Customer()
{
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime? Deleted { get; set; }
}
public partial class MyEntities: DbContext
{
public MyEntities()
: base("name=MyEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Customer> Customers { get; set; }
}
Every time I make an operation on the Customer
DBSet
I really just want to fetch items that have Deleted == null
. This is because the system sometimes will mark Customers as deleted, and then the application should not be aware of these items (as if they didn't exist).
The model is way more complex in reality, which is why I want to control this at the DbContext
-level, rather than adding a Where()
-clause in every query.
Is there any way to always exclude items based upon a column in the table?
Something like so:
public partial class MyEntities: DbContext
{
public MyEntities()
: base("name=MyEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
Customers = Customers.Where(x => x.Deleted == null); // Obviously not working...
}
public virtual DbSet<Customer> Customers { get; set; }
}
Edit: This will be applied to approx 20-30 different entities in a complex model. So I would like to avoid views and manage it in code instead.
Edit 2: Thanks for the tip about EntityFramework.DynamicFilters. However, it doesn't seem to support database first.
Sorry, but when using Database First, we don't have any access to the model configuration so this is not supported.
https://github.com/jcachat/EntityFramework.DynamicFilters/issues/41