EfCore.SoftDeleteServices 开源项目教程

EfCore.SoftDeleteServices 开源项目教程

EfCore.SoftDeleteServicesServices to provide simple soft delete and cascade soft delete in EF Core 项目地址:https://gitcode.com/gh_mirrors/ef/EfCore.SoftDeleteServices

项目介绍

EfCore.SoftDeleteServices 是一个专为 Entity Framework Core 设计的扩展库,它实现了软删除功能,允许开发者在不真正从数据库物理删除记录的情况下,标记数据项为“已删除”。这对于保持数据历史记录完整以及防止误删至关重要。通过集成此库,开发人员可以轻松地在应用程序中实现软删除逻辑,无需手动管理复杂的删除标志。

项目快速启动

要快速开始使用 EfCore.SoftDeleteServices,请遵循以下步骤:

步骤1:安装包

首先,通过NuGet包管理器安装 EfCore.SoftDeleteServices 包:

Install-Package EfCore.SoftDeleteServices

步骤2:配置DbContext

在你的 DbContext 类中引入软删除服务并进行配置:

using JonPSmith.EfCore.SoftDelete;

public class MyDbContext : DbContext, ISoftDeleteDbContext
{
    // ...其他上下文定义...

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        SoftDeleteServices.SetUpSoftDeleting(this, modelBuilder);
    }
}

确保实体类继承自 ISoftDeleteEntity 接口,以启用软删除特性:

using JonPSmith.EfCore.SoftDelete.Entities;

public class User : ISoftDeleteEntity
{
    public int Id { get; set; }
    public string Name { get; set; }

    public bool IsDeleted { get; set; } // 这是由 EfCore.SoftDeleteServices 自动管理的
    // 其他属性...
}

步骤3:使用软删除功能

现在,你可以通过上下文执行软删除操作了:

var user = context.Users.FirstOrDefault();
if (user != null)
{
    context.Remove(user); // 这实际上会标记为软删除,而不是物理删除
    await context.SaveChangesAsync();
}

应用案例和最佳实践

在实际应用中,使用 EfCore.SoftDeleteServices 可以避免因删除造成的数据丢失风险。最佳实践包括:

  • 在查询时默认排除已删除的记录,除非明确指定包含它们。
  • 对于删除操作,始终采用软删除策略,除非有特定需求要求物理删除。
  • 定期清理或归档长时间标记为已删除的记录,以优化性能和存储空间。
// 查询时不包括已删除的记录
var activeUsers = context.Users.Where(u => !u.IsDeleted).ToList();

典型生态项目

虽然直接关联的生态项目不多,但结合其他 EF Core 相关的扩展,如审计日志(例如 EntityFrameworkCore.Tracking)可以增强对数据变更的追踪,从而更好地支持合规性和回溯分析。此外,与ORM框架的高级用法结合,如实体继承和复杂类型处理,能够构建出更灵活且维护性高的数据访问层。


本教程简要介绍了如何集成并利用 EfCore.SoftDeleteServices 提供的软删除功能,帮助您在项目中有效地管理和控制数据生命周期。

EfCore.SoftDeleteServicesServices to provide simple soft delete and cascade soft delete in EF Core 项目地址:https://gitcode.com/gh_mirrors/ef/EfCore.SoftDeleteServices

  • 16
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黎玫洵Errol

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值