【问题标题】:is there a way to check All include navigation befor remove - Entity Framework有没有办法在删除之前检查所有包含导航 - 实体框架
【发布时间】:2016-02-07 06:26:39
【问题描述】:

我有一个 User 类,它有 50 个导航属性(一对多)。例如:

user>>post , user >> files , ...

UserServiceLayer on Delete action 中,我想在删除用户之前检查所有用户navigation Properties,如果其中至少有一个大于零(0),则没有删除权限。

我有SoftDelete

我不想使用If 块来检查所有导航。

有没有办法检查它?或者我应该使用If 声明。

【问题讨论】:

    标签: c# entity-framework ef-code-first entity-framework-6 navigation-properties


    【解决方案1】:

    我会选择这样的:

    public class User
    {
        public int Id { get; set; }
        public bool IsDeleted { get; set; }
        public virtual ICollection<Post> Posts { get; set; }
        public virtual ICollection<File> Files { get; set; }
        // etc...
    
        public bool CanDelete()
        {
            return !Posts.Any() &&
                   !Files.Any(); // &&
                   // etc... 
        }
    }
    

    这将保留用于确定实体是否允许删除的逻辑,您可以在其中更轻松地查看所涉及的属性。

    您仍然需要在 UserServiceLayer 中使用 if 语句,但这将是一个非常简单的 if 语句。


    要制作一个通用版本,一种方法是使用自定义属性和扩展方法,该方法使用反射循环所有标记有该属性的属性。

    这样定义属性:

    [AttributeUsage(AttributeTargets.Property)]
    public class MustBeEmptyToDeleteAttribute : Attribute { }
    

    将属性添加到实体的属性中,如下所示:

    public class User
    {
        public int Id { get; set; }
        public bool IsDeleted { get; set; }
    
        [MustBeEmptyToDelete] public virtual ICollection<Post> Posts { get; set; }
        [MustBeEmptyToDelete] public virtual ICollection<File> Files { get; set; }
        // etc...
    }
    

    最后,为您的实体创建一个扩展类:

    public static class EntityExtensions
    {
        public static bool CanDelete(this object entity)
        {
            return entity.GetType().GetProperties()
                .Where(x => x.IsDefined(typeof(MustBeEmptyToDeleteAttribute)))
                .Select(x => x.GetValue(entity))
                .OfType<IEnumerable<object>>()
                .All(x => !x.Any());
        }
    }
    

    【讨论】:

    • 谢谢。对不起,我有一些像user 这样的课程,我不想为所有课程重复此代码。我可以通用地避免重复此代码吗,例如News 表与NewsTagNewsCommentNewsArchive 和...有关系,我想要一个扩展方法来检查所有
    猜你喜欢
    • 2021-01-24
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多