0

次のエラーが発生しました。 MVC5、EF6、およびWeb APIを使用して INSERTステートメントがASP.net MVC5でAjaxを使用してFOREIGN KEY制約と競合しました

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> 
} 

次マイpostメソッドが似ているさにバインドされたイベント次のように、 しかし、私はgigiIdパラメータが0の値を持つ、なぜそれがあるべき理解していない4の代わりに、あなたはこれだけ属性データ・ギグの値を取得する必要があるプロパティ名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

あなたのリクエスト(ブラウザのネットワークタブで)を調べて、gigIdの値がリクエスト本体に正しく、適切な名前で表示されているかどうか確認しましたか? $ .postコマンドを送信するときに名前を付ける必要があります。 – ADyson

+0

@ADysonこれは[ネットワーク]タブです 'URL:http:// localhost:41230/api /出席者 参照者ポリシー:no-referrer-when-downgrade 要求ヘッダー 暫定ヘッダーが表示されます 承認:*/* コンテンツタイプ:application/x-www-form-urlencoded; User-Agent:Mozilla/5.0(Windows NT 10.0; Win64; x64)AppleWebKit/537.36(charset = UTF-8) 発信元:http:// localhost:41230 Referer:http:// localhost:41230/GeckoのようなKHTML)Chrome/58.0.3029.110 Safari/53736 X-要求-付:XMLHttpRequestを フォームデータ ビューのURLがエンコード ビューソースは 4:します。http:// localhost:41230/API /出席」 – Brainiac

答えて

0

-id。

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

valueOf()を削除し、ajax投稿が機能するときにパラメータ名を追加します。

$.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

これは私が リクエストURLを変更した後、[ネットワーク]タブで得たものです 参照者ポリシー:no-referrer-when-downgrade 要求ヘッダー 暫定ヘッダーが表示されます 承認:*/* コンテンツタイプ:application/x-www-form-urlencoded; User-Agent:Mozilla/5.0(Windows NT 10.0; Win64; x64)AppleWebKit/537.36(charset = UTF-8) 発信元:http:// localhost:41230 Referer:http:// localhost:41230 /ヤモリのようにKHTML、)クローム/ 58.0.3029.110サファリ/ 537.36 X-要求-付:XMLHttpRequestを フォームデータ ビューソース ビューのURLエンコードされた gigId:私は知っていた4 – Brainiac

+0

、使用しないでください**のvalueOf()** –

+0

助けてくれてありがとう。最後に見つかった解決策。私はパラメータ '[FromBody] int gigId'の代わりにDTOオブジェクトを使用して解決しました。そして、はい。私は '.valueOf()'を削除しましたが、うまくいきませんでした。 まだプリミティブ型のパラメータではなくDTOで動作する理由を理解できません。 – Brainiac

1

を追加逃した enter image description here

+0

助けてくれてありがとう。最後に見つかった解決策。私はパラメータ '[FromBody] int gigId'の代わりにDTOオブジェクトを使用して解決しました。そして、はい。私は '.valueOf()'を削除しましたが、うまくいきませんでした。 まだプリミティブ型のパラメータではなくDTOで動作する理由を理解できません。 – Brainiac

0

ありがとうございました。最後に見つかった解決策。私はパラメータ[FromBody] int gigIdの代わりにDTOオブジェクトを使用し、解決しました。そしてはい、私は.valueOf()を削除しましたが、うまくいかなかったのです。

まだプリミティブ型のパラメータではなくDTOで動作する理由を理解できません。

関連する問題