[英]How can I create a generic implementation that lists data from my database?
I've got a large number of tables in my database that are essentially supporting data. 我的数据库中有大量的表,这些表实际上是在支持数据。 These tables list nationalities, genders, languages, etc. and are all based on the same data model:
这些表列出了国籍,性别,语言等,并且都基于相同的数据模型:
public class SupportDataModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool Deleted { get; set; }
}
public class Gender : SupportDataModel
{
}
This data is presented in DropDownList controls mostly so I need to query each table to get a list. 这些数据主要在DropDownList控件中显示,因此我需要查询每个表以获取列表。 Since I don't want to have to rewrite this query every time I need to access the data, I've written it as a helper class:
由于我不需要每次访问数据时都必须重写此查询,因此将其编写为辅助类:
public class GendersHelper : IAlternateHelper<Gender>
{
public List<Gender> ListItems()
{
using (var db = new ApplicationDbContext())
{
return db.Genders.Where(x => !x.Deleted).ToList();
}
}
}
For each of these classes, this function is identical except in the table it queries. 对于这些类中的每一个,此函数都相同,除了查询的表中相同。 That's why I'd like to write a single class that uses the type that I pass in to it as the determining factor for which table I'm querying, but I don't know how to do this.
这就是为什么我想编写一个类,该类使用传入的类型作为要查询的表的确定因素,但我不知道如何执行此操作。
Here's what I've got so far... 到目前为止,这就是我所得到的...
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.
}
}
How do I get this method to determine from the type passed in which table to query and then return a list of those items? 我如何获取此方法以确定要查询的表中传递的类型,然后返回这些项目的列表?
You can just use DbContext.Set<T>
which returns a set for selected type: 您可以只使用
DbContext.Set<T>
来返回所选类型的集合:
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();
}
}
}
However, I wouldn't call this class Helper
, because it looks more like a repository. 但是,我不会将其称为
Helper
类,因为它看起来更像是一个存储库。
Another thing to consider is that you definitely don't want to create an empty class like: 要考虑的另一件事是,您绝对不想创建一个空类,例如:
public class Gender : SupportDataModel
{
}
because it doesn't make much sense. 因为这没有多大意义。 Perhaps, you may want to use
enum
property to define a type of SupportDataModel
. 也许,您可能想使用
enum
属性来定义SupportDataModel
的类型。 In this case, you will have only one table (with more rows though), one simple class with simple repository class and no inheritance or generics. 在这种情况下,您将只有一个表(尽管有更多行),一个具有简单存储库类且没有继承或泛型的简单类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.