I would like to read the contents of several tables into a singleton so that I don't have to keep querying my database for (mostly) static data. When writing the routines to read the database, they all seemed the same so I created a generic method to do so. Works fine.
However, I am unable to assign the results of the table data generically to static members of the singleton. An illustration would probably help. Here's my Singleton class
public sealed class Tables // Sealed so nothing can inherit this class
{
private static Tables instance;
private Tables()
{
}
// Tables to read. Only want to get these once
public static List<Linksmvccore> _alllinks { get; set; } = null;
public static List<Peoplemvc> _allpeople { get; set; } = null;
public static List<Bagsmvc> _allbags { get; set; } = null;
public static List<Country> _allcountries { get; set; } = null;
public static List<Country> _allpertinentcountries { get; set; } = null;
//public static Dictionary<string, List<T> _alltables { get; set; } =
//{
// {"Links", _alllinks }
//}
public static async Task<Tables> GetFromTable<T>(DbSet<T> TableToRead) where T : class
{
if (instance == null)
{
instance = new Tables();
}
if (_alllinks == null) // _alllinks is not generic!!!!
{
var x = await TableToRead.ToListAsync();
_alllinks = x as List<Linksmvccore>; // List<Linksmvccore> is not generic!!!!
}
return instance;
}
}Here is how I call the generic singleton method for the "Links" table
await Tables.GetFromTable(_context.Links);
I attempted to put everything in a static generic data dictionary with no success. I could also put a switch statement into GetFromTable() and load each list based upon typeof(T) but if I someday have hundreds of tables, this seems like a bad idea. Any help appreciated.