问题
I've had success using this code to check all relationships when using Entity Framework ver. 5. (from yildizm85, Entity Framework: Check all relationships of an entity for foreign key use)
public bool IsUnitNameInRelationship(UnitName unitName)
{
bool hasRelation = false;
var allRelatedEnds = ((IEntityWithRelationships)unitName).RelationshipManager.GetAllRelatedEnds();
foreach (var relatedEnd in allRelatedEnds)
{
if (relatedEnd.GetEnumerator().MoveNext())
{
hasRelation = true;
break;
}
}
return hasRelation;
}
After upgrading to EF 6.1.1 it fails. The error message is:
Unable to cast object of type 'System.Data.Entity.DynamicProxies.UnitName_F023365757AB452259D6FFA34E2DC147E423592BFB4A49619F41A60AA3AF5ECA' to type 'System.Data.Objects.DataClasses.IEntityWithRelationships'.
Is there a better approach for checking all relationships using EF 6.1.1?
回答1:
I had the same problem with casting the dynamic proxy instances for entities to the IEntityWithRelationships
interface with EF 6.1.3!
And since I dont have Navigation-Properties for all associated entities of my parent, I came up with this reflection-based code to eventually get the RelationshipManager
instance:
var entityProxy = DbContext.FooBars.First(fb => fb.Id == someId);
var proxyType = entityProxy.GetType();
var wrapperField = proxyType.GetField("_entityWrapper");
var wrapper = wrapperField.GetValue(entityProxy);
var wrapperType = wrapper.GetType();
var relManProp = wrapperType.GetProperty("RelationshipManager");
Debug.Assert(relManProp != null, nameof(relManProp) + " != null");
var relMan = (RelationshipManager)relManProp.GetValue(wrapper);
var allEnds = relMan.GetAllRelatedEnds();
foreach (var relatedEnd in allEnds)
{
Debug.Print("RELATIONSHIP-NAME:" + relatedEnd.RelationshipName);
}
来源:https://stackoverflow.com/questions/24715903/entity-framework-checking-all-relationships-of-an-entity-fails-in-6-1-1