我有以下界面:public interface IInactive{ bool inactive { get; set; }}以及實現該接口的幾個對象(實體框架實體),例如:public class Order : IInactive{ [Key] [Required] public Guid orderId { get; set; } ... public bool inactive { get; set; }} 我正在嘗試實現一個通用方法,該方法可用于僅返回“活動”記錄(即非活動== false)。它將被稱為如下:var query = GetAllActive<Order>();我的這個通用方法的代碼如下所示: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 回答

有只小跳蛙
TA貢獻1824條經驗 獲得超8個贊
由于您的代碼僅適用于繼承自 的記錄IActive,因此對其進行約束。當您這樣做時,屬于該接口的屬性和方法在 的實例中變得可用T。
public IQueryable<T> GetAllActive<T>() where T : IActive //Here is the magic
{
return this._db.Set<T>()
.Where( w => !w.inactive );
}
那不是更容易嗎?
- 1 回答
- 0 關注
- 119 瀏覽
添加回答
舉報
0/150
提交
取消