پیاده سازی حذف منطقی در Entity framework
نویسنده: عثمان رحیمی
تاریخ: ۱۳۹۵/۰۸/۳۰ ۲۳:۵۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public bool IsDeleted { get; set; } public interface ISoftDelete
{
bool IsDeleted { get; set; }
} public class Post :ISoftDelete
{
} where (IsDeleted=false && ...)
public static class EntityFrameworkExtentions
{
public static ObservableCollection<TEntity> Alive<TEntity>(this DbSet<TEntity> set)
where TEntity : class, ISoftDelete
{
var data = set.Where(e => e.IsDeleted == false);
return new ObservableCollection<TEntity>(data);
}
} Install-Package EntityFramework.DynamicFilters
modelBuilder.Filter("IsDeleted", (ISoftDelete d) => d.IsDeleted, false); The DELETE statement conflicted with the REFERENCE constraint ....
public bool CanDelete(user model)
{
return !model.posts.Any() && ! model.news.Any();
} [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());
} public void MarkAsSoftDeleted<TEntity>(TEntity entity) where TEntity : ISoftDelete
{
Entry(entity).State = EntityState.Modified;
// set IsDelete=true
// here you can set other logs like who deleted ,when ,...
}
public void MarkAsDeleted<TEntity>(TEntity entity) where TEntity : class
{
Entry(entity).State = EntityState.Deleted;
} void SetDisableFilter(FilterColumn type);
void SetEnableFilter(FilterColumn type); public void SetDisableFilter(FilterColumn type)
{
switch (type)
{
case FilterColumn.SoftDelete:
this.DisableFilter("IsDeleted");
break;
}
}
public void SetEnableFilter(FilterColumn type)
{
switch (type)
{
case FilterColumn.SoftDelete:
this.EnableFilter("IsDeleted");
break;
}
} public IEnumerable<MyVM> GetAll()
{
total = GetCount();
return _db.Where(filter).ToList();
}
public int GetCount()
{
_uow.SetDisableFilter(Common.FilterColumn.SoftDelete);
int count =_expertises.Count();
_uow.SetEnableFilter(Common.FilterColumn.SoftDelete);
return count;
}