EF ChangeTracker SoftDelete

时间:2017-08-03 03:15:26

标签: c# entity-framework soft-delete

我正在寻找一种更好的方法将以下逻辑(HasAnyRelation和SetDeleteMarks)实现到ChangeTracker中,以避免为我的所有实体重写此逻辑。

问题是,一旦我们调用Remove(),它将删除与子/父实体的所有关系,我无法再检查与ChangeTracker的关系。

In this post我建议在Remove()之后实现我之前实体的副本以保持我的馆藏完好无损。无论如何,我还必须多次实现逻辑。

有人会有任何其他方法来实现它吗?

此致

控制器删除操作

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(Sector sector)
{
    if (ModelState.IsValid)
    {
        var currentEntity = db.Sector.Find(sector.SectorId);
        var hasAnyRelation = EntityHelper.HasAnyRelation(currentEntity);
        if (hasAnyRelation)
        {
            currentEntity = (Sector)EntityHelper.SetDeleteMarks(currentEntity);
            db.Sector.Attach(currentEntity);
            db.Entry(currentEntity).State = EntityState.Modified;
        }
        else
        {
            db.Sector.Attach(currentEntity);
            db.Sector.Remove(currentEntity);
        }

        db.SaveChanges();
    }
}

ENTITY HELPER

public static class EntityHelper
{
public static object SetDeleteMarks(object entityObj)
{
    var deletedProperty = entityObj.GetType().GetProperties().Where(p => p.Name == "Deleted").FirstOrDefault();
    var nameProperties = entityObj.GetType().GetProperties().Where(p => p.Name.Contains("Name"));

    if (deletedProperty != null)
    {
        deletedProperty.SetValue(entityObj, true);
        foreach (var nameProperty in nameProperties)
        {
            var deletedMark = "(*)";
            var currentValue = nameProperty.GetValue(entityObj).ToStringNullSafe();
            if (!currentValue.Contains(deletedMark) && !String.IsNullOrEmpty(currentValue))
            {
                nameProperty.SetValue(entityObj, String.Format("{0} {1}", currentValue, deletedMark).Trim());
            }
        }
    }

    return entityObj;
}

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;
}

private 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);

}

private 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;
}
}

0 个答案:

没有答案