Home > Software design >  is there any way to pre-define a query in a model that runs whenever that model is called from conte
is there any way to pre-define a query in a model that runs whenever that model is called from conte

Time:10-17

i have model in my mvc 5 project named operations.

public class Operation
    {
        public int OperationID { get; set; }
        public string Name { get; set; }
        public decimal Commission { get; set; }
        public int DepartmentID { get; set; }
        public bool CommissionValidity { get; set; }
        public bool IsHidden { get; set; }
        public decimal Capacity { get; set; }
        public virtual Department Department { get; set; }
    }

requirement is whenever this model is called from context like below

Var db = new ApplicationDbContext();
var Operations = db.Operations.tolist();

i want only the records to be loaded where IsHidden field is False without using where clause in query

is there any way like i make constructor or define getter Setter functions to acquire the goal.

CodePudding user response:

If you're using Entity Framework Core, you can use a global query filter to achieve this.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<Operation>().HasFilter(o => !o.IsHidden);
}

Entity Framework 6 doesn't have query filters. For that, you'd need to use a different property on your DbContext to return your visible entities:

public IQueryable<Operation> VisibleOperations 
    => Set<Operation>().Where(o => !o.IsHidden);

However, you won't be able to use this filtered query to add or remove entities from the database, so you'll probably still need to expose the full IDbSet<Operation>, which won't have the filter applied.

  • Related