Bill Haack
Bill Haack

Reputation: 423

Linq query using generics & interfaces

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.

Upvotes: 0

Views: 285

Answers (1)

user3188639
user3188639

Reputation:

Instead of

if (typeof(T) is IInactive)

try

if (typeof(IInactive).IsAssignableFrom(typeof(T)))

Upvotes: 1

Related Questions