在其他实体

时间:2018-02-28 18:37:59

标签: c# asp.net-core entity-framework-core aspnetboilerplate ef-core-2.0

我正在尝试为FullyAuditedEntity实体Test实施硬删除。 Test的主键是Id,它被称为TestTest2实体作为外键。当我尝试从Test实体删除记录时,会出现以下错误。

我已按照this问题进行实施。

TestAppService

public async Task DeleteTest(EntityDto<string> input)
{
    using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.SoftDelete))
    {
        await _TestRepository.DeleteTest(input);
        CurrentUnitOfWork.SaveChanges();
    }
}

TestRepository

public async Task DeleteArticle(EntityDto input)
{
    await DeleteAsync(x => x.Id == input.Id);
}

TestTest2

[Table("TestTest2")]
public class TestTest2 : FullAuditedEntity
{
    [ForeignKey("TestId")]
    public virtual Test Test { get; set; }
    public virtual string TestId { get; set; }

    [ForeignKey("Test2Id")]
    public virtual Test2Details Test2s { get; set; }
    public virtual int Test2Id { get; set; }
}

MyProjectDbContextModelSnapshot

modelBuilder.Entity("MyCompany.MyProject.Business.Model.Tests.TestTest2Association", b =>
{
    b.HasOne("MyCompany.MyProject.Business.Model.Tests.Test", "Test")
        .WithMany()
        .HasForeignKey("TestId");

    b.HasOne("MyCompany.MyProject.Business.Model.Test2s.Test2Details", "Test2s")
        .WithMany()
        .HasForeignKey("Test2Id")
        .OnDelete(DeleteBehavior.Cascade);
});
  

ERROR 2018-02-28 18:10:09,840 [26]   Mvc.ExceptionHandling.AbpExceptionFilter - 发生错误   更新条目。有关详细信息,请参阅内部异常   Microsoft.EntityFrameworkCore.DbUpdateException:发生错误   在更新条目时。有关详细信息,请参阅内部异常---&GT;   System.Data.SqlClient.SqlException:DELETE语句发生冲突   使用REFERENCE约束&#34; FK_TestTest2_Test_TestId&#34;。冲突   发生在数据库&#34; MyProjectDb&#34;,table&#34; dbo.TestTest2&#34;,列   &#39; TestId&#39 ;.该语句已终止。在   System.Data.SqlClient.SqlConMyCompanytion.OnError(SQLEXCEPTION   exception,Boolean breakConMyCompanytion,Action 1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConMyCompanytion.OnError(SqlException exception, Boolean breakConMyCompanytion, Action 1 wrapCloseInAction)   在   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject   stateObj,Boolean callerHasConMyCompanytionLock,Boolean asyncClose)
  在System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,   SqlCommand cmdHandler,SqlDataReader dataStream,   BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject   stateObj,布尔&amp; dataReady)at   System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()at   System.Data.SqlClient.SqlDataReader.get_MetaData()at   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,   RunBehavior runBehavior,String resetOptionsString)at   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(的CommandBehavior   cmdBehavior,RunBehavior runBehavior,Boolean returnStream,Boolean   async,Int32超时,任务&amp; task,Boolean asyncWrite,SqlDataReader   ds)at   System.Data.SqlClient.SqlCommand.RunExecuteReader(的CommandBehavior   cmdBehavior,RunBehavior runBehavior,Boolean returnStream,   TaskCompletionSource 1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader() at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConMyCompanytion conMyCompanytion, DbCommandMethod executeMethod, IReadOnlyDictionary 2   parameterValues)at   Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConMyCompanytion   conMyCompanytion,IReadOnlyDictionary 2 parameterValues) at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConMyCompanytion conMyCompanytion) --- End of inner exception stack trace --- at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConMyCompanytion conMyCompanytion) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple 2   参数)at   Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute [TSTATE,TResult](TSTATE   state,Func 3 operation, Func 3 verifySucceeded)at   Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute [TSTATE,TResult](IExecutionStrategy   策略,TState状态,Func 2 operation) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable 1   commandBatches,IRelationalConMyCompanytion conMyCompanytion)at   Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList 1 entries) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList 1   entriesToSave)at   Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(布尔   acceptAllChangesOnSuccess)at   Microsoft.EntityFrameworkCore.DbContext.SaveChanges(布尔   acceptAllChangesOnSuccess)at   Abp.EntityFrameworkCore.AbpDbContext.SaveChanges()in   d:\ Github上\ aspnetboilerplate的\ src \ Abp.EntityFrameworkCore \ EntityFrameworkCore \ AbpDbContext.cs:行   198点   Abp.Zero.EntityFrameworkCore.AbpZeroCommonDbContext`3.SaveChanges()in   d:\ Github上\ aspnetboilerplate \ SRC \ Abp.ZeroCore.EntityFrameworkCore \零\ EntityFrameworkCore \ AbpZeroCommonDbContext.cs:线   154点   Abp.EntityFrameworkCore.Uow.EfCoreUnitOfWork.SaveChangesInDbContext(的DbContext   dbContext)in   d:\ Github上\ aspnetboilerplate \ SRC \ Abp.EntityFrameworkCore \ EntityFrameworkCore \ UOW \ EfCoreUnitOfWork.cs:线   159 Abp.EntityFrameworkCore.Uow.EfCoreUnitOfWork.SaveChanges()   在   d:\ Github上\ aspnetboilerplate \ SRC \ Abp.EntityFrameworkCore \ EntityFrameworkCore \ UOW \ EfCoreUnitOfWork.cs:线   60点到   MyCompany.MyProject.Business.Services.Tests.TestAppService.d__12.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__12.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__10.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext   上下文)   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(州及放大器;   接下来,范围&amp;范围,对象&amp; state,Boolean&amp; isCompleted)at   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__14.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__23.MoveNext()   INFO 2018-02-28 18:10:09,873 [26]   etCore.Mvc.Internal.ObjectResultExecutor - 执行ObjectResult,   写作值Microsoft.AspNetCore.Mvc.ControllerContext。信息   2018-02-28 18:10:09,922 [26]   ore.Mvc.Internal.ControllerActionInvoker - 执行的动作   MyCompany.MyProject.Business.Services.Tests.TestAppService.DeleteTest   (MyCompany.MyProject.Business.Services)在3940.4091ms INFO   2018-02-28 18:10:10,158 [26]   soft.AspNetCore.Hosting.Internal.WebHost - 请求已完成   4037.4507ms 500 application / json;字符集= UTF-8

注意:应删除TestTest2表中的条目。

更新

下面的安装工作得很好,但我有一些特殊的要求。 Test实体Id正在其他表格中引用,例如TestTest2TestTest3TestTest4TestTest5。当我从Test表中删除记录时,它应该从所有表中删除。 但我还需要调用其他依赖表(例如TestTest2TestTest3TestTest4TestTest5)删除方法以执行特定于此的额外清理实体(例如TestTest2TestTest3TestTest4TestTest5)。

TestRepository

public async Task DeleteTest(EntityDto input)
{
    await DeleteAsync(input.Id);

    _TestTest2Repository.Delete(x => x.TestId == input.Id);
    _TestTest3Repository.Delete(x => x.TestId == input.Id);
    _TestTest4Repository.Delete(x => x.TestId == input.Id);
    _TestTest5Repository.Delete(x => x.TestId == input.Id);
}

1 个答案:

答案 0 :(得分:2)

来自Cascade Delete的文档:

  

对于可选关系: ClientSetNull (默认)
   - 对数据库中依赖/子项的影响:无

您必须在DbContext中使用Fluent API配置删除行为:

modelBuilder.Entity<TestTest2>()
            .HasOne(t => t.Test)
            .WithMany()
            .OnDelete(DeleteBehavior.Cascade);