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?
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);
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With