0

I have several entity framework classes that implement the following an IInactive interface.

public interface IInactive
{
    bool inactive { get; set; }
}

For example, my Order class is defined as follows:

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 against all objects (entities) whether they implement the IInactive interface or not. 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>();

    // Does the entity implement the IInactive interface.
    // If yes, only return "active" row, otherwise return all rows
    if (typeof(T)is IInactive)
    {
        // Problem: the code in this block never executes, that is,
        // (typeof(T)is IInactive) never evaluates to true

       ...

    }

    return dbSet;
}

I would greatly appreciate some help solving this issue! Thanks.

4
  • Start with where T : class, IInactive and see where that takes you. Even if it doesn't solve this exact problem, you can skip the implementation check and prevent callers from using entity types that don't support this check (it's enforced by the compiler and the runtime!). Commented Aug 21, 2019 at 22:27
  • Thanks, but I actually want to be able to call this method for all entities, even those that do not implement IInactive. If the class does not implement IInactive, I want to return all records. Commented Aug 21, 2019 at 22:33
  • I have an idea but I have to test it to make sure it'll work. If it works and you don't have an answer yet, I'll post it. Commented Aug 21, 2019 at 22:41
  • Thanks madreflection, much appreciated. Commented Aug 21, 2019 at 22:45

1 Answer 1

1

Instead of

if (typeof(T) is IInactive)

try

if (typeof(IInactive).IsAssignableFrom(typeof(T)))
Sign up to request clarification or add additional context in comments.

3 Comments

Tom - Thanks that did the trick on the first issue. That's a new one for me. Any ideas on how to cast IQueryable<IInactive> to IQueryable<T>? Thanks!
@BillHaack this is a completely different question
Fair enough, I edited the question to just include the 1st issue. I will create a second post for for the other issue.

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.