SaveChanges()之后,“ DELETE语句与REFERENCE约束EF核心发生冲突”

时间:2019-06-11 11:18:11

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

我正在将Entity Framework Core与.net core 2.2一起使用,并且遇到一个奇怪的间歇性问题。

在我的情况下,我有这三个带有实体的表(简化了): 数据模型:

public class Case : BaseEntity
    {
        public int CaseId { get; set; }
        public Guid ClientId { get; set; }
        public virtual Client Client { get; set; }
    }
    public class Client : BaseEntity
    {
        public Guid ClientId { get; set; }
        public Guid PersonId { get; set; }
    public virtual ICollection<Case> Case { get; set; }
    }

配置:

modelBuilder.Entity<Case>(entity =>
            { entity.HasOne(d => d.Client).WithMany(p => p.Case).HasForeignKey(d => d.ClientId).OnDelete(DeleteBehavior.Restrict);
});

为了在代码中添加新的Case,我正在做这样的事情:

1. Begin the transaction

2. Calling a SP in which I am adding a client and adding some dependenttable info and returning the ClientId from  it.

3. I am passing the client Id to next step as mentioned below:

objCase.Client=objClient;
objCase.ClientId=objClient,ClientId;
_Context.Client.Add(objCase);

4. Now I am calling the below methods which is throwing the exception
_context.SaveChanges();

到目前为止,此方法运行良好,并在Client表中创建了具有ID和personId的新条目,并在Case表中创建了具有将Client链接到企业的条目的新条目。

突然我遇到了一个用户(但不是另一个)的错误,该错误将代码挂起一段时间,然后给出以下异常:

  

SqlException:DELETE语句与REFERENCE约束“ FK_Case_Client_ClientId”冲突。在数据库“ CenterManagementSystem”的表“ dbo.Case”的“ ClientId”列中发生了冲突。

     

该语句已终止。

完整的AppInsight:

Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.RemoteDependency","time":"2019-06-11T10:30:42.1388220Z","sampleRate":50,"tags":{"ai.application.ver":"1.0.0.0","ai.cloud.roleInstance":"ICEN083","ai.operation.id":"e18f8d7fa6aecf448350d74dea9ceedb","ai.operation.parentId":"|e18f8d7fa6aecf448350d74dea9ceedb.65995757_","ai.operation.name":"POST Clients/PostCase [clientId/orgId]","ai.location.ip":"::1","ai.internal.sdkVersion":"rdddsc:2.9.1-26132","ai.internal.nodeName":"ICEN083"},"data":{"baseType":"RemoteDependencyData","baseData":{"ver":2,"name":"servername | CenterManagementSystem","id":"0602a78dd80f4716a98e37f9fa8c9c91","data":"SET NOCOUNT ON;\r\nDELETE FROM [Client]\r\nWHERE [ClientId] = @p0;\r\nSELECT @@ROWCOUNT;","duration":"00:00:02.5031198","resultCode":"547","success":false,"type":"SQL","target":"servername | CenterManagementSystem","properties":{"AspNetCoreEnvironment":"qa","DeveloperMode":"true","_MS.ProcessedByMetricExtractors":"(Name:'Dependencies', Ver:'1.1')","Exception":"System.Data.SqlClient.SqlException (0x80131904): The DELETE statement conflicted with the REFERENCE constraint \"FK_Case_Client_ClientId\". The conflict occurred in database \"CenterManagementSystem\", table \"dbo.Case\", column 'ClientId'.\r\nThe statement has been terminated.\r\n   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()\r\n   at System.Data.SqlClient.SqlDataReader.get_MetaData()\r\n   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n   at System.Data.Common.DbCommand.ExecuteReader()\r\n   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)\r\nClientConnectionId:58a6c6e2-b1a8-41ea-93a3-f8fbce2035d3\r\nError Number:547,State:0,Class:16"}}}}

我想我的主要问题是,为什么实体框架在执行插入过程中试图删除某些内容?

非常感谢您提供任何见解,帮助或指导。

0 个答案:

没有答案