- 实现DbContext的软删除功能
- dotnet add package Biwen.EFCore.SoftDelete --version 1.1.1
- Windows 10
- Visual Studio 2022 / Visual Studio Code
- .NET 8.0
[PrimaryKey("Id")]
public class Blog : ISoftDeleted
{
//...
public int Id { get; set; }
public string Title { get; set; } = null!;
public string Content { get; set; } = null!;
public int AuthorId { get; set; }
//请注意这里的IsDeleted默认必须是false!表示未删除
public bool IsDeleted { get; set; } = false;
}
public class TestDbContext : SoftDeleteDbContext
{
public TestDbContext(DbContextOptions<TestDbContext> options)
: base(options)
{
}
//...
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
//根据情况自定义表名
//...
}
}
var serviceProvider = new ServiceCollection()
.AddDbContext<TestDbContext>(options =>
{
//使用你的数据库引擎
options.UseInMemoryDatabase("test");
})
.BuildServiceProvider();
//1. 请使用 DbSet.Remove() 方法,不可使用批量删除方法:ExecuteDelete(),ExecuteDeleteAsync()
//Delete 1 模拟软删除
var blog1 = db.Blogs.FirstOrDefault(x => x.Id == 1);
db.Remove(blog1!);
db.SaveChanges();
//Delete 3 模拟强制删除
var blog3 = db.Blogs.FirstOrDefault(x => x.Id == 3);
db.Remove(blog3!, true);
db.SaveChanges();
- MIT
- QQ:552175420
- Email: vipwan#outlook.com
- [GitHub](https://github.com/vipwan)