0

我收到以下錯誤。使用MVC5,EF6和web api的 。INSERT語句與使用ASP.net中的Ajax的FOREIGN KEY約束衝突MVC5

INSERT語句與FOREIGN KEY約束「FK_dbo.Attendances_dbo.Gigs_GigId」衝突。衝突發生在數據庫「aspnet-GigHub-20170521125426」,表「dbo.Gigs」,列'Id'中。

{System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Attendances_dbo.Gigs_GigId". The conflict occurred in database "aspnet-GigHub-20170521125426", table "dbo.Gigs", column 'Id'. 
The statement has been terminated. 
    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) 
    at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) 
    at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) 
    at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) 
    at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption) 
    at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) 
    at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) 
    at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) 
    at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() 
    at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c) 
    at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) 
    at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext) 
    at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery() 
    at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues) 
    at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() 
    --- End of inner exception stack trace --- 
    at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() 
    at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter. <Update>b__2(UpdateTranslator ut) 
    at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction) 
    at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update() 
    at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35() 
    at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) 
    at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) 
    at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27() 
    at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation) 
    at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) 
    at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) 
    at System.Data.Entity.Internal.InternalContext.SaveChanges() 
    --- End of inner exception stack trace --- 
    at System.Data.Entity.Internal.InternalContext.SaveChanges() 
    at System.Data.Entity.Internal.LazyInternalContext.SaveChanges() 
    at System.Data.Entity.DbContext.SaveChanges() 
    at GigHub.Controllers.AttendancesController.Attend(Int32 gigId) in D:\Visual studio 2017 online projects\GigHub\GigHub\Controllers\AttendancesController.cs:line 39} 

我有以下出勤模型類

using System.ComponentModel.DataAnnotations; 
using System.ComponentModel.DataAnnotations.Schema; 

namespace GigHub.Models 
{ 
    public class Attendance 
    { 
     public Gig Gig { get; set; } 
     public ApplicationUser Attendee { get; set; } 

     [Key] 
     [Column(Order = 1)] 
     public int GigId { get; set; } 

     [Key] 
     [Column(Order = 2)] 
     public string AttendeeId { get; set; } 
    } 
} 

事件綁定到下面的按鈕 enter image description here

腳本按鈕事件處理是繼

@section scripts{ 

    <script> 
     $(document).ready(function() { 
      $(".js-toggle-attendance").click(function(e) { 
       var button = $(e.target); 
       $.post("/api/Attendances/", button.attr("data-gig-id").valueOf()) 
        .done(function() { 
         button.removeClass("btn-default").addClass("btn-info").text("Going"); 
        }) 
        .fail(function() { 
         alert('Something Failed'); 
        }); 
      }); 
     }); 
    </script> 
} 

我交的方法是像如下, ,但我不明白爲什麼gigiId參數具有0值應該是4,而不是 enter image description here

+0

您是否檢查了您的請求(在瀏覽器的網絡選項卡中)以查看gId值是否正確地位於請求正文中並且名稱正確?我認爲您需要在發送$ .post命令時給它命名 – ADyson

+0

@ADyson這是我的網絡標籤 '請求URL:http:// localhost:41230/api /考勤 引用策略:no-referrer-when-downgrade 請求標頭 臨時標頭顯示 接受:*/* 內容類型:application/x-www-form-urlencoded;用戶代理:Mozilla/5.0(Windows NT 10.0; Win64; x64)AppleWebKit/537.36(UTF-8編碼)UTF-8 產地:http:// localhost:41230 Referer:http:// localhost:41230/Home/Index KHTML,像Gecko)Chrome/58.0.3029.110 Safari/537。36 X-請求-隨着:XMLHttpRequest的 表單數據 視圖源 視圖URL編碼 4:」 – Brainiac

回答

0

你錯過添加屬性名gigId

<script> 
     $(document).ready(function() { 
      $(".js-toggle-attendance").click(function(e) { 
       var button = $(e.target); 
       $.post("/api/Attendances/", { "gigId": button.attr("data-gig-id") }) 
        .done(function() { 
         button.removeClass("btn-default").addClass("btn-info").text("Going"); 
        }) 
        .fail(function() { 
         alert('Something Failed'); 
        }); 
      }); 
     }); 
    </script> 
+0

這是我得到了在網絡標籤改變 請求URL後:HTTP://本地主機:41230/API /出勤 推薦人政策:no-referrer-when-downgrade 請求標頭 臨時標頭顯示 接受:*/* 內容類型:application/x-www-form-urlencoded;用戶代理:Mozilla/5.0(Windows NT 10.0; Win64; x64)AppleWebKit/537.36(UTF-8編碼)UTF-8 產地:http:// localhost:41230 Referer:http:// localhost:41230/Home/Index KHTML,例如Gecko)鉻/ 58.0.3029.110 Safari瀏覽器/ 537.36 X-請求-隨着:XMLHttpRequest的 表單數據 視圖源 視圖URL編碼 gigId:4 – Brainiac

+0

我知道,不使用**的valueOf()** –

+0

感謝您的幫助。終於找到解決方案我已經使用DTO對象而不是參數'[FromBody] int gigId'並解析。是的,我已經刪除了'.valueOf()',但沒有成功。 仍然不明白它爲什麼與DTO協同工作,而不是基本類型參​​數。 – Brainiac

1

你只需要這個來獲得屬性數據,演出的價值-ID。

button.attr("data-gig-id") 

刪除valueOf()並在ajax post可能工作時添加參數名稱。

$.post("/api/Attendances", { "gigId": button.attr("data-gig-id") }) 
       .done(function() { 
        button.removeClass("btn-default").addClass("btn-info").text("Going"); 
       }) 
       .fail(function() { 
        alert('Something Failed'); 
       }); 
+0

感謝您的幫助。終於找到解決方案我已經使用DTO對象而不是參數'[FromBody] int gigId'並解析。是的,我已經刪除了'.valueOf()',但沒有成功。 仍然不明白它爲什麼與DTO協同工作,而不是基本類型參​​數。 – Brainiac

0

感謝您的幫助。終於找到解決方案我已經使用了DTO對象而不是參數[FromBody] int gigId並解決了它。是的,我已經刪除.valueOf(),但它沒有奏效。

仍然不明白它爲什麼與DTO協同工作,而不是原始類型參數。

相關問題