0

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]'.'

}
1
  • Do you actually need to make this method generic as your code will always query against an IInactive and hence why not convert your method signature to public IQueryable<IInactive> GetAllActive() Commented Aug 22, 2019 at 0:36

1 Answer 1

2

Since your code only works with records that inherit from IActive, constrain it as such. When you do that, the properties and methods belonging to the interface become available in instances of T.

public IQueryable<T> GetAllActive<T>() where T : IActive  //Here is the magic
{
    return this._db.Set<T>()
        .Where( w => !w.inactive );
}

Isn't that easier?

Sign up to request clarification or add additional context in comments.

9 Comments

Sorry John, in an effort to simplify the question I left out some code. I cannot do: public IQueryable<T> GetAllActive<T>() where T : IInactive because I want the method to be able to accept non-IInactive objects.
@BillHaack How would you filter classes that don't have the inactive property?
@juharr if (typeof(IInactive).IsAssignableFrom(typeof(T)))
@BillHaack You know that this is exactly what I originally suggested, right?
I went ahead and accepted the solution. Even though this was not exactly what I was looking for, it turns out it is probably the best solution to the problem. @madreflection, sorry should have accepted your solution when you offered it up in the previous question!!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.