c# - How can I find the Id property or properties related to a navigational property? -


for project i'm working entity framework , i'd able enumerate navigational properties given object instance (assuming it's object generated ef). there i'd related id property every navigational property.

for example, if instance of class person, want able find it's navigational properties called address , boss. 2 navigational properties want "lookup" related id properties called addressid , bossid.

i need id properties can run queries on different database not have same foreign keys have same ids.

so far have figured out way relationshipmanager random object instance generated ef. , while debugging can foreign key relations via manager's relationships property. can far navigational property name. can see there's fk_person_address related navigational property called address can't find addressid.

so question is, how can dynamically (with no knowledge of person class' layout) discover addressid property related address?

i aware foreign key relationship might have id property on other side of relation (boss pointing person in stead of person having bossid). in case, i'd still discover boss has personid when i'm inspecting instance of person.

this give dictionary navigation properties key , related properties value (the value might property other entity)

add these dbcontext class , call db.getforeignkeyproperties<person>()

the result like:

"address" - "addressid"

"boss" - "person.bossid"

public dictionary<string,string> getforeignkeyproperties<dbtype>() {     entitytype table = gettableentitytype<dbtype>();     dictionary<string, string> foreignkeys = new dictionary<string, string>();      foreach (navigationproperty np in table.navigationproperties)     {         var association = (np.toendmember.declaringtype associationtype);         var constraint = association.referentialconstraints.firstordefault();            if (constraint != null && constraint.torole.getentitytype() == table)             foreignkeys.add(np.name, constraint.toproperties.first().name);          if (constraint != null && constraint.fromrole.getentitytype() == table)             foreignkeys.add(np.name, constraint.toproperties.first().declaringtype.name+"."+constraint.toproperties.first().name);     }      return foreignkeys; }  private entitytype gettableentitytype<dbtype>() {     return gettableentitytype(typeof(dbtype)); }  private entitytype gettableentitytype(type dbtype) {     objectcontext objcontext = ((iobjectcontextadapter)this).objectcontext;     metadataworkspace workspace = objcontext.metadataworkspace;     entitytype table = workspace.getedmspacetype((structuraltype)workspace.getitem<entitytype>(dbtype.fullname, dataspace.ospace)) entitytype;     return table; } 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -