Bill Haack
Bill Haack

Reputation: 423

Linq query using generics & interfaces casting issue

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

}

Upvotes: 0

Views: 82

Answers (1)

John Wu
John Wu

Reputation: 52250

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?

Upvotes: 2

Related Questions