Retrieve Primary Key Fieldnames

3 posts, 0 answers
  1. Nikolai Hellwig
    Nikolai Hellwig avatar
    16 posts
    Member since:
    Mar 2010

    Posted 08 Apr 2010 Link to this post

    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. Nikolai Hellwig
    Nikolai Hellwig avatar
    16 posts
    Member since:
    Mar 2010

    Posted 08 Apr 2010 Link to this post

    sorry,

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

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

    thanks
  3. DevCraft banner
  4. PetarP
    Admin
    PetarP avatar
    754 posts

    Posted 08 Apr 2010 Link to this post

    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.
Back to Top