c# – How to pass a table name to a function as a parameter?

Question:

I am using Entity Framework. There is a certain function in which the dataGridView is filled with data from the table.

private void data()
{
    using (Context context = new Context())
    {
        var items = from Items in context.Table1
                    select Items;

        dataGridView1.DataSource = items.ToList();
    }
}

But I want to make a generic function so that the table name is passed through a parameter. Can you tell me how to modify the function to make this possible?

Something like this:

void Test()
{
    data(tbl1);
    data(tbl2);
}

private void data(SomeType tableName)
{
    using (Context context = new Context())
    {
        var items = from Items in tableName
                    select Items;

        dataGridView1.DataSource = items.ToList();
    }
}

Answer:

If the type of entities in the tables is the same, then you can try to run a function to select a table as a parameter:

void Test()
{
    data(c => c.tbl1);
    data(c => c.tbl2);
}

private void data(Func<Context, IQueryable<SomeType>> tableSelector)
{
    using (Context context = new Context())
    {
        var items = from Items in tableSelector(context)
                    select Items;

        dataGridView1.DataSource = items.ToList();
    }
}

If different – add a generic parameter

private void data<T>(Func<Context, IQueryable<T>> tableSelector)
{
    using (Context context = new Context())
    {
        var items = from Items in tableSelector(context)
                    select Items;

        dataGridView1.DataSource = items.ToList();
    }
}

not tested live, typos possible

If you need to pass the table name exactly as a string, you will have to use reflection. Try to avoid it 🙂

Scroll to Top