• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 663
  • Last Modified:

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

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

Ken Fayal
Ken Fayal
1 Solution
You can use Reflection to do that.
//first getting assembly
Assembly assem = Assembly.LoadFrom("fullname");
Type t = assem.GetType("typename");
Hey Kenbo...

From your query I think you are looking for something like this?
var pkName = dc.Mapping.GetTables()
                .Where(c => c.TableName == _tableName)

Open in new window

Ken FayalCTOAuthor Commented:
Yes!!! This was it!  Thank you!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now