亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用泛型和接口轉換問題的 Linq 查詢

使用泛型和接口轉換問題的 Linq 查詢

C#
小唯快跑啊 2023-09-16 16:57:53
我有以下界面: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 );

}

那不是更容易嗎?


查看完整回答
反對 回復 2023-09-16
  • 1 回答
  • 0 關注
  • 119 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號