问题
I want to get the foreign key value for a navigation property, without having to define the foreign key property (before the navigation property is loaded).
Why?
We cache (for instance) all "status"-objects application wide (yes we couldn't use enums for this). When we load an object with a navigation property to this status-class the repository will set the property to the cached item.
I could go with a foreign key property, but since EF knows the key, I would like to get it from EF (maybe through the RelationshipManager or the DBEntityReference for the navigation property) but I can't seem to find it.
Note: I am using EF5, code first in .Net 4.5
回答1:
I found an answer (on stackoverflow) from Slauma (not sure if I should mark this as duplicate?). I had to change the code a litle to handle an entity with multiple relations. A lot of stuff is still ugly but it works :)
RelationshipManager relMgr = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.GetRelationshipManager(document);
IEnumerable<IRelatedEnd> relEnds = relMgr.GetAllRelatedEnds();
IRelatedEnd relEnd = relEnds.Where(r => r.RelationshipName.EndsWith("Document_Status")).Single();
EntityReference<Status> entityRef = relEnd as EntityReference<Status>;
var entityKey = entityRef.EntityKey;
short statusId =(short)entityKey.EntityKeyValues[0].Value;
The only downside is that (As far as I can tell. Hope someone finds a better way?) this information is lost as soon as you detach the entity or when you load it with AsNoTracking().
来源:https://stackoverflow.com/questions/13451766/ef-5-get-foreign-key-value-for-navigation-property