Ken Fayal
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?
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.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Yes!!! This was it! Thank you!
You can use Reflection to do that.
//first getting assembly
Assembly assem = Assembly.LoadFrom("fullnam
Type t = assem.GetType("typename");