我有一组基于实体框架 (EF) 的存储库,其中一些处理可以软删除的实体(并非所有实体都可以)。实体由 EF 自动生成。到目前为止,我有:
可以软删除的实体实现了 ICanBeSoftDeleted 接口:
public interface ICanBeSoftDeleted { bool IsDeleted { get; set; } }
对于这些实体,我使用实现 ISoftDeleteRepository 的存储库:
public interface ISoftDeleteRepository<T> : IRepository<T> where T : class, ICanBeSoftDeleted { void SoftDelete(T entity); void SoftDelete(Expression<Func<T, bool>> where); }
我还有一个基类 SoftDeleteRepositoryBase,它扩展了 RepositoryBase 并添加了软删除方法:
public abstract class SoftDeleteRepositoryBase<T> : RepositoryBase<T> where T : class, ICanBeSoftDeleted { public virtual void SoftDelete(T entity) { entity.IsDeleted = true; Update(entity); } public virtual void SoftDelete(Expression<Func<T, bool>> where) { var entitiesToDelete = GetMany(where).AsEnumerable(); foreach (T entity in entitiesToDelete) { this.Delete(entity); } } }
这一切都很好。但是,此代码是分发给直接调用存储库的用户的内部库的一部分,我不希望他们更改“IsDeleted”属性,只读取它或删除调用该方法的实体。现在他们可以这样做,因为 setter 是公开的。
我怎样才能改变我的代码设计才能做到这一点?我无法更改 ICanBeSoftDeleted 并删除设置器,因为那样我将无法从 SoftDeleteRepositories 修改它。
谢谢
更新:目前我已经通过从界面中删除“set”并使用反射设置存储库中的值来解决问题:
public virtual void Delete(T entity)
{
PropertyInfo propertyInfo = entity.GetType().GetProperty("IsDeleted");
propertyInfo.SetValue(entity, true);
Update(entity);
}
然而,这对我来说就像一个补丁,我不认为它解决了更大的设计问题......