簡體   English   中英

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

[英]Entity Framework Generic Lookup based on Type

我有一個包含許多表的數據庫,這些表是純粹的只讀查找。 它們都是 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; }

有人可以建議我哪里出錯了嗎?

您提供的代碼是嵌套DbSet

您所展示的是將T解析為:

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

你的T需要是一個普通的實體類。 刪除GetLookup方法上的DbSet泛型約束並添加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>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM