基于类型的实体框架通用查找

我有一个数据库,其中有许多表,这些表纯粹是只读查找。它们都是 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; }

有人可以建议我哪里出了问题吗?


慕桂英4014372
浏览 107回答 1
1回答

尚方宝剑之说

您提供的代码正在嵌套DbSet.您所展示的内容正在解决T此问题:context.Set<DbSet<BedType>>();您T需要是一个普通的实体类。删除DbSet该方法的通用约束GetLookup并添加一个class。public List<LookupModel> GetLookupList<T>() where T : class{&nbsp; &nbsp; try&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; using (var context = new TwoCEntities())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var rows = context.Set<T>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return rows.Select(row => new LookupModel&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Id = (int)row.GetType().GetProperty("Id").GetValue(row, null),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Description = row.GetType().GetProperty("Description").GetValue(row, null).ToString()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).ToList();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; catch (Exception e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (log.IsErrorEnabled) log.ErrorFormat("GetLookupList<{0}> raised exception {1} with message {2}", typeof(T), e.GetType(), e.Message);&nbsp; &nbsp; &nbsp; &nbsp; throw;&nbsp; &nbsp; }}这将使您的类型变量T解析为方法中的以下内容。context.Set<BedType>();当你调用它时,请像这样使用它:var result = lookupRepository.GetLookupList<BedType>();
打开App,查看更多内容
随时随地看视频慕课网APP