Heidi T.
Heidi T.

Reputation: 75

dynamic table name in Entity

I want to call method with Table name like db.users.select(x=> x.FirstName) , but i made a mistake somewhere , i write like this but this returns detail about table on one row , not return table data which i want, help please

    public void LoadToGrid(string dbTableName)
    {
      dataGridView1.DataSource = db.GetType().GetMember(dbTableName).ToList();    
    }

Upvotes: 1

Views: 1843

Answers (1)

Transcendent
Transcendent

Reputation: 5755

Your question isn't very clear, but if you mean that You wanna do it in a generic way, then yes that is possible. You can take advantage of the Set<T> method. For example:

public void LoadToGrid<T>(GridType grid) where T: class, new() {
    grid.DataSource = dbContext.Set<T>().ToList();
}

And to customize the data fields in your grid, your can add this overload

public void LoadToGrid<T>(GridType grid, Expression<Func<T,Object>> selectExpression) where T: class, new() {
    grid.DataSource = dbContext.Set<T>().Select(selectExpression).ToList();
}

Upvotes: 3

Related Questions