如何级联SoftDelete?

时间:2016-08-17 13:48:51

标签: c# entity-framework-6 soft-delete

检查这些SO文章后:cascade-delete-in-entity-frameworkef6-1-soft-delete-with-cascade-deletecascading-soft-deletemethod-for-cascading-soft-deletes-in-parent-child-relationshipsreasons-for-cascading-soft-deletes,但未找到解决方案......

我有SoftDelete为我的实体模型工作。我在上下文中覆盖了CREATE TABLE #TblFinal (F_ID INT IDENTITY(1,1), F_VAL NVARCHAR(20), F_SEV_ID INT, F_U_KEY NVARCHAR(200), F_COUNTER INT DEFAULT(1), F_IS_CLEAR BIT DEFAULT(0)) CREATE TABLE #TblData (D_ID INT, D_VAL NVARCHAR(20), D_SEV_ID INT, D_U_KEY NVARCHAR(200)) INSERT INTO #TblData VALUES(1, 'test 1', 2, '1:100002135::::15124:9334'), (2, 'test 1', 2, '1:100002135::::15124:9334'), (3, 'test', -11, '1:100002135::::15124:9334'), (4, 'test 1', 2, '1:100002135::::15124:9334'), (5, 'test 1', 2, '1:1024:9334') DECLARE @D_ID INT DECLARE @D_SEV_ID INT DECLARE @D_U_KEY NVARCHAR(200) DECLARE A_CUR CURSOR FOR SELECT D_ID, D_SEV_ID, D_U_KEY FROM #TblData ORDER BY D_ID ASC OPEN A_CUR FETCH NEXT FROM A_CUR INTO @D_ID, @D_SEV_ID, @D_U_KEY WHILE @@FETCH_STATUS = 0 BEGIN IF EXISTS(SELECT 1 FROM #TblFinal(NOLOCK) WHERE F_U_KEY = @D_U_KEY AND F_IS_CLEAR = 0 AND F_SEV_ID <> -11) BEGIN DECLARE @FId INT SELECT @FId = F_ID FROM #TblFinal(NOLOCK) WHERE F_U_KEY = @D_U_KEY AND F_IS_CLEAR = 0 AND F_SEV_ID <> -11 --IF @D_SEV_ID != -11 IF (@D_SEV_ID <> -11) BEGIN UPDATE #TblFinal SET F_COUNTER = F_COUNTER + 1 WHERE F_ID = @FId END --IF @D_SEV_ID = -11 ELSE IF(@D_SEV_ID = -11) BEGIN INSERT INTO #TblFinal (F_VAL, F_SEV_ID, F_U_KEY) SELECT D_VAL, D_SEV_ID, D_U_KEY FROM #TblData(NOLOCK) WHERE D_ID = @D_ID UPDATE #TblFinal SET F_IS_CLEAR = 1 WHERE F_ID = @FId END ELSE BEGIN PRINT 'DO NOTHING' END END ELSE BEGIN INSERT INTO #TblFinal (F_VAL, F_SEV_ID, F_U_KEY) SELECT D_VAL, D_SEV_ID, D_U_KEY FROM #TblData(NOLOCK) WHERE D_ID = @D_ID END FETCH NEXT FROM A_CUR INTO @D_ID, @D_SEV_ID, @D_U_KEY END CLOSE A_CUR DEALLOCATE A_CUR --SELECT * FROM #TblData SELECT * FROM #TblFinal DROP TABLE #TblData DROP TABLE #TblFinal

SaveChanges()

我为我的孩子实体设置了CascadeOnDelete。因为我覆盖了已删除的 public override int SaveChanges() { ChangeTracker.DetectChanges(); foreach (DbEntityEntry<ISoftDeletable> entity in ChangeTracker.Entries<ISoftDeletable>()) { if (entity.State == EntityState.Deleted) { entity.State = EntityState.Modified; entity.Entity.IsDeleted = true; } } return base.SaveChanges(); } ,所以它不会级联。有人知道将导航属性放在EntityState循环中的方法吗?还是处理SoftDeletes的更好方法?

提前谢谢你,

1 个答案:

答案 0 :(得分:2)

阅读此SO文章entity-framework-6-code-first-cascade-delete ...

我意识到,我抓住并删除了我的实体:

var entity = context.Parent.FirstOrDefault();
context.Parent.Remove(entity);

当我需要像这样抓取整个图表时:

var entity = context.Parent.Include("Children").FirstOrDefault();
context.Parent.Remove(entity);

感谢您输入@Maarten