Reputation: 495
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
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
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