LindDotNetCore ~ ISoftDelete soft deletion interface,
Back to directory
Concept
ISoftDelete is a soft delete. Data is not cleared from the database after being deleted, but only marked as a state, which cannot be obtained within the business scope, this is relatively easy to implement in the ORM framework. for traditional ado, unified SQL interception and conditional filtering are required.
Implementation steps code implementation
1. The entity inherits ISoftDelete.
protected override void OnModelCreating(ModelBuilder modelBuilder){ foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { // 1. Add the IsDeleted property entityType.GetOrAddProperty("IsDeleted", typeof(bool)); // 2. Create the query filter var parameter = Expression.Parameter(entityType.ClrType); // 3. EF.Property<bool>(post, "IsDeleted") var propertyMethodInfo = typeof(EF).GetMethod("Property").MakeGenericMethod(typeof(bool)); var isDeletedProperty = Expression.Call(propertyMethodInfo, parameter, Expression.Constant("IsDeleted")); // 4. EF.Property<bool>(post, "IsDeleted") == false BinaryExpression compareExpression = Expression.MakeBinary(ExpressionType.Equal, isDeletedProperty, Expression.Constant(false)); // 5. post => EF.Property<bool>(post, "IsDeleted") == false var lambda = Expression.Lambda(compareExpression, parameter); modelBuilder.Entity(entityType.ClrType).HasQueryFilter(lambda);
2. Implement IsDeleted Filtering Based on Data Context
public class ProductInfo : EntityBase, ISoftDelete{ public string Title { get; set; } public decimal Amount { get; set; } public int Discount { get; set; } public int Inventory { get; set; } public DateTime DeletedDate { get; set; } public string DeletedUser { get; set; } public bool IsDeleted { get; set; } /// <summary> /// domain method /// </summary> /// <returns></returns> public decimal GetSaleAmount() { return Amount * Discount / 100; }}
3. Adjust the deletion method and add support for ISoftDelete.
The Code comes from the Lind. DotNetCore. Repository. EFRepository type.
Public void Delete (TEntity item) {if (item! = Null) {if (typeof (ISoftDelete ). isAssignableFrom (item. getType () {Db. entry (item ). state = EntityState. modified; var delEntity = item as ISoftDelete; delEntity. deletedDate = DateTime. now; delEntity. isDeleted = true;} else {// Delete the database physically. set <TEntity> (). attach (item as TEntity); Db. entry (item ). state = EntityState. deleted; Db. set <TEntity> (). remove (item as TEntity);} this. saveChanges ();}}
The above lines of code provide complete support for soft Delete, from the ISoftDelete interface to the IsDeleted filtering in the data context, to the optimized Delete () method. Everything looks elegant!
There are also a lot of frameworks supported for soft deletion, such as abp, es‑conationer, and linddotnetcore!
Welcome to read and think!
Back to directory