c# - 如何创建一个列出数据库中数据的通用实现?
问题描述
我的数据库中有大量表,它们基本上是支持数据的。这些表格列出了国籍、性别、语言等,并且都基于相同的数据模型:
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.
}
}
如何让这个方法从传入的类型中确定要查询的表,然后返回这些项目的列表?
解决方案
您可以只使用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
. 在这种情况下,您将只有一个表(尽管有更多行),一个具有简单存储库类且没有继承或泛型的简单类。
推荐阅读
- python - 使用多个数据集训练神经网络 (Keras)
- python - Numba 数据类型错误:无法统一数组
- java - 有没有办法解密从特定表中散列成 CRC int 的字符串?
- python - Matplotlib 绘制比例三角形
- sql-server - 每个字符串的长度正好是 100 个字符
- javascript - 你如何打印出你输入的输入文本的值?Javascript 和 HTML
- python - 我如何使用 python 下载 youtube 视频
- c++11 - C++:使用 Youcompleteme 自动完成工具的 Vim 编辑器 - 不列出标准标题
- android - ANDROID:- 谷歌支付行动选择器不工作
- r - 使用 Rvest 从多个页面中抓取文本、表格并将两者结合起来