Ortund
Ortund

Reputation: 8245

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. 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?

Upvotes: 0

Views: 113

Answers (1)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

You can just use DbContext.Set<T> which returns a set for selected type:

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.

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. 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.

Upvotes: 2

Related Questions