dotnet add package Biwen.EFCore.SoftDelete --version 1.1.1
[ 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 ;
}
Step 2 继承SoftDeleteDbContext
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 ( ) ;
QQ:552175420
Email: vipwan#outlook.com