Entity Framework 5 - select only objects in which the IsActive object

Using the Code First approach, I created several different objects that inherit from the IConcurrent interface using the IsActive property, for example:

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

Every time I select objects, I always have to include a conditional sentence, such as this real basic example:

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

My question is, can I somehow intercept / insert in DbContext so that my LINQ queries always return IsActive == true for objects inheriting the IConcurrent interface so that there is no explicit addition of .Where(c => c.IsActive) each time?

So far, I have been considering possible overriding methods in DbContext that none of them seem to match the count. Can anyone help?

+4
source share
2 answers

You can use filtering in Set<> to get only active instances, something like strings:

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

This method can be included in a class that inherits the DbContext class, or you can make it in an extension method, for example:

 public static DbContextExtensions { public static IQueryable<T> GetActive<T>(this DbContext context) where T : class, IConcurrent { return context.Set<T>().Where(e => e.IsActive); } } 
+4
source

Conditional mapping is supported in the Model First approach, but it is not directly supported in the first code approach. Perhaps you have a workaround by creating a property in DBContext similar to the following:

 public IQueryable<Currency> ActiveCurrencies { get { db.Currencies.Where(c => c.IsActive); } } 
+4
source

All Articles