Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 5 - only select entities where entity IsActive

Using the Code First approach I have created a number of different entities that inherit from an interface IConcurrent with a property IsActive for example:

public class Currency : IConcurrent
{
    public string CurrencyId { get; set; }

    public string Description { get; set; }

    public bool IsActive { get; set; }
}

Each time I select entities I find myself always having to include a conditional clause such as this real basic example:

db.Currencies.Where(c => c.IsActive);

My question is that is it possible to some how intercept/hook into the DbContext so that my LINQ queries will always return IsActive == true for entities that inherit the IConcurrent interface, to avoid having to explicitly add .Where(c => c.IsActive) each time?

So far I've looked at the possible methods to override in DbContext which none of them seem to fit the bill. Can anyone help?

like image 561
Stokedout Avatar asked Feb 18 '23 17:02

Stokedout


2 Answers

You can use filtering on the Set<> method to get just active instances, something along the lines of:

public IQueryable<T> GetActive<T>() where T : class, IConcurrent
{
   return Set<T>().Where(e => e.IsActive);
}

This method could be included in a class that inherits the DbContext class, or you could make it into an extension method, like:

public static DbContextExtensions
{
  public static IQueryable<T> GetActive<T>(this DbContext context) 
    where T : class, IConcurrent
  {
     return context.Set<T>().Where(e => e.IsActive);
  }
}
like image 189
SWeko Avatar answered Apr 27 '23 06:04

SWeko


Conditional mapping is supported in Model First approach but it is not directly supported in Code first approach. You may have a workaround by creating a property in DBContext similar to the following;

public IQueryable<Currency> ActiveCurrencies 
{
    get 
    {
        db.Currencies.Where(c => c.IsActive);
    }
}
like image 37
daryal Avatar answered Apr 27 '23 06:04

daryal