0

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?

Community
  • 1
  • 1

1 Answers1

2

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);
} 
w00zla
  • 21
  • 4
  • I think you need to be a bit careful with using `var wrapperField = proxyType.GetField("_entityWrapper");` because if your database contains alot of records (say more than 100000 rows) then you will get a bit performance issue. – Gwasshoppa Mar 11 '21 at 02:54