I have the following interface:
public interface IInactive
{
bool inactive { get; set; }
}
And several objects (entity framework entities) that implement that interface, such as:
public class Order : IInactive
{
[Key]
[Required]
public Guid orderId { get; set; }
...
public bool inactive { get; set; }
}
I am trying to implement a generic method that can be used to return only "active" records (i.e. inactive == false). It would be called as follows:
var query = GetAllActive<Order>();
My code for this generic method looks like this:
public IQueryable<T> GetAllActive<T>() where T : class
{
DbSet<T> dbSet = this._db.Set<T>();
IQueryable<IInactive> query2 = dbSet as IQueryable<IInactive>;
query2 = query2.Where(w => !w.inactive);
return (DbSet <T>)query2;
// System.InvalidCastException: 'Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[Portal.Domain.Entities.Interfaces.IInactive]' to type 'System.Data.Entity.DbSet`1[Portal.Domain.Entities.Order]'.'
}
public IQueryable<IInactive> GetAllActive()