Feed Subscribe
Exception has been thrown by the target of an invocation.

Match foreign key property with navigation property in Entity Framework metadata

by ondrejsv 31. August 2010 17:04

Entity Framework 4 brought a new way of dealing with references – directly through their foreign key value. While it takes off some abstraction, it’s more friendly to common situations in practice (e.g. selecting from drop down lists) and also it enables you to change a reference without having to load either the old referenced entities or the new one. Also note that this feature is optional; you won’t have your model polluted with foreign keys if you do not want.

This brings some new challenges in my scripts and old code dealing with EF metadata. Now I have to differentiate between “ordinary” simple properties and foreign key properties. Fortunately, it’s not that difficult.

You can get the matching foreign key property to a given navigation property by calling the GetDependentProperties() method which returns exactly entity properties which are dependent ones in the relationship. Note that we’re playing in the conceptual model area (which is what I want) and the foreign key column as implemented in the database could have different name. Also note that if there is a foreign key property, the method should return only value. If there isn’t (maybe you unchecked the “Include foreign key columns in the model” option in the Data Model Wizard), the collection will be empty.

And as usual some code for demonstration. It just outputs the list of all navigation properties in all entities and their corresponding foreign key property names:

var cx = new ModelContainer(); var mw = cx.MetadataWorkspace; var entities = mw.GetItems<EntityType>(DataSpace.CSpace); foreach (var en in entities) { Console.WriteLine(en.FullName); foreach (var np in en.NavigationProperties) { Console.WriteLine("- navigation property found: " + np.Name); if (np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One || np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One) { Console.WriteLine("-- is to one"); Console.WriteLine("--- its FK property is " + np.GetDependentProperties().ToList()[0].Name); } } }


Comments are closed