This is a migrated thread and some comments may be shown as answers.

Retrieve Primary Key Fieldnames

2 Answers 79 Views
Development (API, general questions)
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Nikolai Hellwig
Top achievements
Rank 1
Nikolai Hellwig asked on 08 Apr 2010, 10:21 AM
Hi,

Let's say i have a class generated by the reverse mapping tool named "Land".

How could i figure out in code which fields belong to the primary key, without typing the name of the table?

I'd like to write a generic method, so i don't want to change it everytime a new table is added to the project.

ex.    Input = class ie. type, Output = primary key fieldnames (propertynames in case of c#)

thanks
Nikolai Hellwig
CHW Software GmbH

2 Answers, 1 is accepted

Sort by
0
Nikolai Hellwig
Top achievements
Rank 1
answered on 08 Apr 2010, 12:27 PM
sorry,

i found a solution by myself. I have to use: 

IPersistentTypeDescriptor desc = scope.PersistentMetaData.GetPersistentTypeDescriptor(typeof(Land));

thanks
0
PetarP
Telerik team
answered on 08 Apr 2010, 12:31 PM
Hello Nikolai Hellwig,

The easiest way would be to traverse our metadata tree and extract the primary keys from there. Here is a sample method that can be used to extract the primary keys for each of your persistent types:
static void Main(string[] args)
       {
           NorthwindEntityDiagrams db = new NorthwindEntityDiagrams();
           List<string> primaryKeys = ExtractPrimaryKeysForType(typeof(OrderDetail), db);
           foreach (string primaryKey in primaryKeys)
           {
               Console.WriteLine(primaryKey);
           }
 
       }
       private static List<string> ExtractPrimaryKeysForType(Type type, OpenAccessContext db)
       {
           MetaPersistentType persistentType = db.Metadata.PersistentTypes.Where(c => c.FullName == type.FullName).First(); //Selects the Persistent type from the metadata
           return persistentType.Members.Where(c => (c is MetaPrimitiveMember) && (c as MetaPrimitiveMember).IsIdentity == true).Select(c => c.PropertyName).ToList(); //Retrieves a list of the primary keys
       }


All the best,
Petar
the Telerik team

Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
Tags
Development (API, general questions)
Asked by
Nikolai Hellwig
Top achievements
Rank 1
Answers by
Nikolai Hellwig
Top achievements
Rank 1
PetarP
Telerik team
Share this question
or