Solved

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

Posted on 2009-05-13
3
636 Views
Last Modified: 2013-11-11
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

0
Comment
Question by:Ken Fayal
3 Comments
 
LVL 13

Expert Comment

by:dungla
ID: 24381034
Hi,
You can use Reflection to do that.
//first getting assembly
Assembly assem = Assembly.LoadFrom("fullname");
Type t = assem.GetType("typename");
0
 
LVL 7

Accepted Solution

by:
deadlyDev earned 500 total points
ID: 24448786
Hey Kenbo...

From your query I think you are looking for something like this?
var pkName = dc.Mapping.GetTables()
                .Where(c => c.TableName == _tableName)
                .Single()
                .RowType.IdentityMembers[0].Name;

Open in new window

0
 
LVL 9

Author Closing Comment

by:Ken Fayal
ID: 31581264
Yes!!! This was it!  Thank you!
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question