加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 具有软删除功能的通用存储库

发布时间:2020-12-16 03:28:01 所属栏目:asp.Net 来源:网络整理
导读:我有一个通用的存储库实现.我正在使用asp.net mvc c#,代码第一个实体框架. 我创建了一个名为ISoftDelete的接口: public interface ISoftDelete{ bool IsDeleted { get; set; }} 我在我的基础存储库中实现了Delete和GetById,如下所示: public virtual void
我有一个通用的存储库实现.我正在使用asp.net mvc c#,代码第一个实体框架.

我创建了一个名为ISoftDelete的接口:

public interface ISoftDelete
{
    bool IsDeleted { get; set; }
}

我在我的基础存储库中实现了Delete和GetById,如下所示:

public virtual void Delete(T entity)
    {
        if (entity is ISoftDelete)
        {
            ((ISoftDelete)entity).IsDeleted = true;
        }
        else
        {
            dbset.Remove(entity);
        }
    }

    public virtual T GetById(long id)
    {
        T obj = dbset.Find(id);
        if (obj is ISoftDelete)
        {
            if (((ISoftDelete)obj).IsDeleted)
                return null;
            else
                return obj;
        }
        else
        {
            return obj;
        }
    }

现在,我有2个问题.

1)这种方法是一种好方法吗?任何性能相关的问题?

2)我在基础存储库中的原始GetAll函数是这样的:

public virtual IEnumerable<T> GetAll()
    {
            return dbset.ToList();
    }

当从ISoftDelete派生T时,如何修改它以便列出IsDeleted == false的记录?

谢谢!

解决方法

1)每次你需要知道它时,检查是否(实体是ISoftDelete)似乎没有问题.如果你确定你不打算在其他地方检查它可能没问题.就性能而言,如果您删除具有IsDeleted == true且永远不会从db获取它们的记录,那会更好.您可能需要派生一个新的基本存储库,它会覆盖这些方法并为ISoftDelete对象实现新的逻辑.

public abstract class BaseRepository<T>
{
    // protected dbset;

    public virtual void Delete(T entity)
    {
        dbset.Remove(entity);
    }

    public virtual T GetById(long id)
    {
        return dbset.Find(id);
    }

    public virtual IEnumerable<T> GetAll()
    {
        return dbset.ToList();
    }
}

public abstract class SoftDeleteRepository<T> : BaseRepository<T> where T : ISoftDelete
{
    public override void Delete(T entity)
    {
         entity.IsDeleted = true;
    }

    public override T GetById(long id)
    {
        return (from t in dbSet
                where !t.IsDeleted && t.Id == id select t)
                .FirstOrDefault();
    }

    public override IEnumerable<T> GetAll()
    {
        return (from t in dbset where !t.IsDeleted select t).ToList();
    }
}

public static class RepositoryFactory
{
     public static BaseRepository<T> GetInstance<T>()
     {
          // pseudo code
          if (typeof(T) implements ISoftDelete)
               return repository of T which extends SoftDeleteRepository
          return repository of T which extends BaseRepository
     }
}

2)可能是这样的

return (from t in dbset  where 
       (t is ISoftDelete && !(t as ISoftDelete).IsDeleted) || 
       !(t is ISoftDelete))
 .ToList();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读