Link to home
Start Free TrialLog in
Avatar of Ken Fayal
Ken FayalFlag for United States of America

asked on

Get Primary Key of table using only string type table name in Linq

Hello,
I'm having trouble with obtaining the primary key using the LINQ datacontext and when I only have the table name in a string variable.  What I am trying is below, but it doesn't work because I can't get the Type argument of GetTable

I'm building a dynamic table editor using the GridView control and LINQDataSource as the datasource so I need to get the primary key of the table being edited so I can assign it to the GridView.DataKeyNames property.

Anyone run into this?
//This works because I write the actual entity name 'MainTable' in the code:
 
string pkName = _dc.Mapping.GetTable(typeof(MainTable)).RowType.IdentityMembers[0].Name;
 
//But I want to dynamically get the primary key of a table that is stored in a string variable.
//I have tried this:
 
Type tableType = Type.GetType("My.Namespace.." + _tableName);
pkName = _dc.Mapping.GetTable(typeof(tableType)).RowType.IdentityMembers[0].Name;
 
//This doesn't work because it wants an actual class name in the GetTable() method.

Open in new window

Avatar of dungla
dungla
Flag of Viet Nam image

Hi,
You can use Reflection to do that.
//first getting assembly
Assembly assem = Assembly.LoadFrom("fullname");
Type t = assem.GetType("typename");
ASKER CERTIFIED SOLUTION
Avatar of deadlyDev
deadlyDev
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ken Fayal

ASKER

Yes!!! This was it!  Thank you!