Reputation: 437
The class which all my entities inherit from looks like this:
public class EntityBase
{
public DateTimeOffset? CreatedDate { get; set; }
public DateTimeOffset? LastModifiedDate { get; set; }
public string Status { get; set; }
}
what I'm trying to accomplish is for EF to automatically filter out any Status which is "Deleted" any time I bring back results from the database. With the searching I've done I've found the common way to do this is by override OnModelCreating In the Db context class like so:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<EntityBase>().Map(m => m.Requires("Status").HasValue("Active"));
base.OnModelCreating(modelBuilder);
}
This is problematic for a couple reasons. First and foremost it doesn't work. As soon as I touch the database I get the error:
EntityType 'EntityBase' has no key defined. Define the key for this EntityType. EntityBases: EntityType: EntitySet 'EntityBases' is based on type 'EntityBase' that has no keys defined.
Which is accurate, my base entity does not have a key. However, it's also not an actual table in my DB so it's not supposed to.
My other problem is that this is not actually the filter I want. This uses .HasValue("Active")
when I'm looking for more of a .DoesntHaveValue("Deleted")
.
Upvotes: 1
Views: 674
Reputation: 437
Ended up going with the Query Filter suggestion from @ivan-stoev and attached it to the Context constructor. Heres the code for posterity.
using Z.EntityFramework.Plus;
...
public MyContext() : base("MyContext")
{
this.Filter<EntityBase>(q => q.Where(x => x.Status != "Deleted"));
}
Upvotes: 1