首页 > 解决方案 > 如何创建一个列出数据库中数据的通用实现?

问题描述

我的数据库中有大量表,它们基本上是支持数据的。这些表格列出了国籍、性别、语言等,并且都基于相同的数据模型:

public class SupportDataModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Deleted { get; set; }
}
public class Gender : SupportDataModel
{
}

此数据主要显示在 DropDownList 控件中,因此我需要查询每个表以获取列表。因为我不想每次需要访问数据时都重写这个查询,所以我把它写成一个帮助类:

public class GendersHelper : IAlternateHelper<Gender>
{
    public List<Gender> ListItems()
    {
        using (var db = new ApplicationDbContext())
        {
            return db.Genders.Where(x => !x.Deleted).ToList();
        }
    }
}

对于这些类中的每一个,这个函数都是相同的,除了它查询的表中。这就是为什么我想编写一个单独的类,它使用我传递给它的类型作为我要查询的表的决定因素,但我不知道该怎么做。

这是我到目前为止所得到的......

public abstract class SupportingDataHelper<T>
{
    public List<T> ListItems()
    {
        // Logic to determine which table gets queried,
        // as well as the query itself should go here.
    }
}

如何让这个方法从传入的类型中确定要查询的表,然后返回这些项目的列表?

标签: c#genericsabstract-class

解决方案


您可以只使用DbContext.Set<T>which 返回所选类型的集合:

public class SupportDataRepository<T> where T : SupportDataModel
{
    public List<T> ListItems()
    {
        using (var db = new ApplicationDbContext())
        {
            return db.Set<T>().Where(x => !x.Deleted).ToList();
        }
    }
}

但是,我不会调用这个类Helper,因为它看起来更像是一个存储库。

要考虑的另一件事是,您绝对不想创建一个空类,例如:

public class Gender : SupportDataModel
{
}

因为它没有多大意义。也许,您可能想使用enum属性来定义SupportDataModel. 在这种情况下,您将只有一个表(尽管有更多行),一个具有简单存储库类且没有继承或泛型的简单类。


推荐阅读