Entity Framework: Check all relationships of an entity for foreign key use

后端 未结 4 768
广开言路
广开言路 2020-12-29 11:20

I have an entity, let\'s call it CommonEntity that has a primary key used as a foreign key in many other entities. As the application is developed these links w

相关标签:
4条回答
  • 2020-12-29 11:54

    You can try this:

    var allrelatedEnds = ((IEntityWithRelationships)ce).RelationshipManager.GetAllRelatedEnds();
    bool hasRelation = false;
    foreach (var relatedEnd in allrelatedEnds)
    {
        if (relatedEnd.GetEnumerator().MoveNext())
        {
            hasRelation = true;
            break;
        }
    }
    
    if (!hasRelation)
    {
        //Delete
    }
    
    0 讨论(0)
  • 2020-12-29 11:58

    First find the entity which you want to delete using Find in EF and pass the entity to below function.. If the function returns true it means cannot be deleted and foreign data exists.. If function returns false it means no parent or child records and can be delete..

     public static bool DeleteCheckOnEntity(object entity)
       {
         var propertiesList = entity.GetType().GetProperties();
         return (from prop in propertiesList where prop.PropertyType.IsGenericType select prop.GetValue(entity) into propValue select propValue as IList).All(propList => propList == null || propList.Count <= 0);
       }
    
    0 讨论(0)
  • 2020-12-29 12:01

    Just let it fail. If the entity has many relationships, that verification could be really heavy.

    public bool TryDelete(int id)
    {
        try
        {
            // Delete
            return true;
        }
        catch (SqlException ex)
        {
            if (ex.Number == 547) return false; // The {...} statement conflicted with the {...} constraint {...}
            throw; // other error
        }
    }
    
    0 讨论(0)
  • 2020-12-29 12:01

    You can use Reflection for this (if you don't want use "Fail Delete On SQL") I write this because I dont want to DELETE Entity, just want to know if its related to any or not !

     public static object GetEntityFieldValue(this object entityObj, string propertyName)
            {
                var pro = entityObj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).First(x => x.Name == propertyName);
                return pro.GetValue(entityObj, null);
    
            }
    
     public static IEnumerable<PropertyInfo> GetManyRelatedEntityNavigatorProperties(object entityObj)
            {
                var props = entityObj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.CanWrite && x.GetGetMethod().IsVirtual && x.PropertyType.IsGenericType == true);
                return props;
            }
    
    public static bool HasAnyRelation(object entityObj)
            {
    
                    var collectionProps= GetManyRelatedEntityNavigatorProperties(entityObj);
    
    
                    foreach (var item in collectionProps)
                    {
                        var collectionValue = GetEntityFieldValue(entityObj,item.Name);
                        if (collectionValue != null && collectionValue is IEnumerable)
                        {
                            var col = collectionValue as IEnumerable;
                            if (col.GetEnumerator().MoveNext())
                            {
                                return true;
                            }
    
                        }
                    }
                   return false;
    }
    

    NOTE that : Context must not Disposed and Proxy Must Be Enabled AND KNOW THAT IT WILL GET ALL RELATED RECORD TO MEMORY (IT'S Too Heavy)

    0 讨论(0)
提交回复
热议问题