Reputation: 495
I have code below, it used to pull object "Applicant" (table Applicant) properties.
void Main()
{
PropertyInfo[] props = typeof(Applicant).GetProperties();
foreach (PropertyInfo prop in props)
{
prop.Name.Dump();
}
}
The result are:
EthnicBackground
Distance
TransplantHospital
Appointments
Employers
Claims
EthnicBackground, Distance, TransplantHospital are Applicant's parent tables.
Appointments, Employers, Claims are Applicant's son tables.
Right now the result are parent tables and son tables mixed together.
How to modify the code, separate the output result by parent tables and son tables automatics?
The Applicant class construction base on database table Applicant like below:
Upvotes: 0
Views: 67
Reputation: 16067
I think the PropertyType should be either typeOf(T)
or typeOf(EntitySet<T>)
depending on the type of relationship. Hence you can probably distinguish the two by looking to see if the type has any generic arguments, ie something like :
PropertyInfo[] props = typeof(Applicant).GetProperties();
var parents = (from r in props
where r.PropertyType.GenericTypeArguments.Count() == 0
select r.Name)
.ToList().Dump();
var children = (from r in props
where r.PropertyType.GenericTypeArguments.Count() == 1
select r.Name)
.ToList().Dump();
Upvotes: 1
Reputation: 1208
In the loop you can check PropertyInfo.DeclaringType property. so the code would become (roughly)
void Main()
{
PropertyInfo[] props = typeof(Applicant).GetProperties();
foreach (PropertyInfo prop in props)
{
if (prop.DeclaringType == typeof(Applicant))
{
// this is an Applicant property
string name = prop.Name;
// TODO: store wherever you need
}
else
{
// this is a parent table property
string name = prop.Name;
// TODO: store wherever you need
}
}
}
Upvotes: 0