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

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

基于類型的實體框架通用查找

基于類型的實體框架通用查找

C#
慕桂英4014372 2023-06-25 14:35:50
我有一個數據庫,其中有許多表,這些表純粹是只讀查找。它們都是 2 列:相同類型的 ID 和描述。我想創建一個通用方法,它將 DbSet 類型作為 T 并從適當的表返回到標準 LookupModel 類。這是我所得到的:    public List<LookupModel> GetLookupList<T>() where T : DbSet    {        try        {            using (var context = new TwoCEntities())            {                var rows = context.Set<T>();                return rows.Select(row => new LookupModel                {                    Id = (int)row.GetType().GetProperty("Id").GetValue(row, null),                    Description = row.GetType().GetProperty("Description").GetValue(row, null).ToString()                }).ToList();            }        }        catch (Exception e)        {            if (log.IsErrorEnabled) log.ErrorFormat("GetLookupList<{0}> raised exception {1} with message {2}", typeof(T), e.GetType(), e.Message);            throw;        }    }我的問題是調用它。這不會編譯:var result =  lookupRepository.GetLookupList<DbSet<BedType>>();我收到這個錯誤The type 'System.Data.Entity.DbSet<Repository.BedType>' cannot be used as type parameter 'T' in the generic type or method 'ILookupRepository.GetLookupList<T>()'. There is no implicit reference conversion from 'System.Data.Entity.DbSet<Repository.BedType>' to 'System.Data.Entity.DbSet'.BedType 在我的上下文中定義為public virtual DbSet<BedType> BedType { get; set; }有人可以建議我哪里出了問題嗎?
查看完整描述

1 回答

?
尚方寶劍之說

TA貢獻1788條經驗 獲得超4個贊

您提供的代碼正在嵌套DbSet.


您所展示的內容正在解決T此問題:


context.Set<DbSet<BedType>>();

您T需要是一個普通的實體類。刪除DbSet該方法的通用約束GetLookup并添加一個class。


public List<LookupModel> GetLookupList<T>() where T : class

{

    try

    {

        using (var context = new TwoCEntities())

        {

            var rows = context.Set<T>();

            return rows.Select(row => new LookupModel

            {

                Id = (int)row.GetType().GetProperty("Id").GetValue(row, null),

                Description = row.GetType().GetProperty("Description").GetValue(row, null).ToString()

            }).ToList();

        }

    }

    catch (Exception e)

    {

        if (log.IsErrorEnabled) log.ErrorFormat("GetLookupList<{0}> raised exception {1} with message {2}", typeof(T), e.GetType(), e.Message);

        throw;

    }

}

這將使您的類型變量T解析為方法中的以下內容。


context.Set<BedType>();

當你調用它時,請像這樣使用它:


var result = lookupRepository.GetLookupList<BedType>();


查看完整回答
反對 回復 2023-06-25
  • 1 回答
  • 0 關注
  • 135 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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