Search code examples
c#entity-frameworklinqgridviewreusability

Use type derived from GetType() without using Switch


I am using Entity Framework and LINQ. I want to create a reusable method in a "helper" class for GridViews.

The method will return a DataSource as a List of entities based off the type of entity passed.

So GridView1 will show [Entity1]'s so the call will look like:

GridView1.DataSource = helperClass.GetDataSource(new Entity1());

Note* If I should pass the entity type I want as a string in the method I am open for suggestion. I just don't want to have to use a switch case between the ~40 entity types this method could return

The reusable method will be simple and look similar to:

public static object GetDataSource(object type)
{
    using (DatabaseContext dc = new DatabaseContext())
    {
        if (dc.[how do I get the entity type here].Count() > 0)
        {
            var modelList = dc.[how do I get the entity type here also].ToList();
        }
    }
}

This will sound silly, but obviously I wasn't able to do:

var modelList = dc.(type.GetType()).ToList();

but that is basically what I want to accomplish.


Solution

  • This approach was not plausible and I ended up storing the datasource of the GridView in a SessionState variable. Saved having to requery for the DataSource each postback (could get tedious if I had to keep track of order bys when requerying. instead the sessionstate variable keeps the sort order)