Deep in Development
Deep in Development

Reputation: 495

How to get parent tables and children tables plus table primary key by retrieve table object properties?

I have code below (credit:sgmoore). It use to extract table's Parents table and Children table.

void Main()
{
    PropertyInfo[] props = typeof(Product).GetProperties();

    var parents = (from r in props
                  where r.PropertyType.GenericTypeArguments.Count() == 0
                  select r.Name)
                  .ToList().Dump("Parents Tables");

    var children = (from r in props
                   where r.PropertyType.GenericTypeArguments.Count() == 1
                   select r.Name)
                   .ToList().Dump("Children Tables");
}

The result are :

Parents Tables :

Category, Supplier

Children Tables :

OrderDetails, Carts, Reviews

enter image description here

Thanks Sgmoore provide above code. Right now I want make the output like parents/children table name plus table primary key. Who can provide the solution will be great appreciate.

Upvotes: 0

Views: 110

Answers (1)

sgmoore
sgmoore

Reputation: 16067

The following routine should give you the primary key for any table in your DataContext

public static string GetPrimaryKey(DataContext dc , string tableName)
{        
    var table =  (from t in dc.Mapping.GetTables() where t.TableName == tableName || t.TableName == "[" + tableName + "]" select t).Single();

    return (from r in table.RowType.DataMembers where r.IsPrimaryKey select r.Name).Single();
}

So you could use this like

PropertyInfo[] props = typeof(Bank).GetProperties();

var parents = (from r in props 
               where r.PropertyType.GenericTypeArguments.Count() == 0 
               let TableName = r.PropertyType.Name
               select new { Column = r.Name  , TableName  , PrimaryKey = GetPrimaryKey(this, TableName) } )
               .ToList().Dump();

var children = (from r in props 
                where r.PropertyType.GenericTypeArguments.Count() == 1 
                let TableName = r.PropertyType.GenericTypeArguments.Single().Name
                select new { Column = r.Name  , TableName  , PrimaryKey = GetPrimaryKey(this , TableName) } )
               .ToList().Dump();

Not sure whether this is the best way, but it should work.

Upvotes: 1

Related Questions