Harbie
Harbie

Reputation: 23

Using generics for :get all" queries

I am trying to use generics to reduce the number of stored procedures in my database, which I have successfully done. The problem comes in the next step. The DB columns are mapped to a model and all tables have an ID column. I want to create a hashtable with the ID field ad the key and the model as the object. When i try to do this I get a compile-time error that T does not have a definition for ID. Is there a way to do this?

public static class DB_TableToHashTable
    {
        public static Hashtable dbTableToHashTable<T>(string tableName)
        {
            List<T> myList = GlobalConfig.Connection.GenericGetAll<T>(tableName);
            Hashtable table = new Hashtable();
            foreach (var item in myList)
            {

                table.Add(item.ID, item);

            }

            return table;
        }
    }

Upvotes: 1

Views: 69

Answers (1)

Guru Stron
Guru Stron

Reputation: 142288

If all of the id fields are of the same type you can define an interface IHaveId and use constraints on type parameters :

public interface IHaveId
{
   public int ID {get;}
}

public static Hashtable dbTableToHashTable<T>(string tableName) where T : IHaveId

Upvotes: 2

Related Questions