2017-03-02 11 views
0

DbInitializerを実行すると、 "context.SaveChanges"でエラーが表示され、 "Microsoft.EntityFrameworkCore.DbUpdateException ' Microsoft.EntityFrameworkCore.dllで発生しましたが、ユーザーコードで処理されませんでした。 "コード実行時に "DbUpdateExceptionがユーザーコードによって処理されませんでした"というエラーが発生する

いくつかの異なるNuGetパッケージをダウンロードしましたが、それでもエラーは残ります。何か案は ?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using Microsoft.EntityFrameworkCore; 
using Microsoft.Extensions.DependencyInjection; 
using FinalTeamProject.Data; 

namespace FinalTeamProject.Models 
{ 
public static class DbInitializer 
{ 
    public static void Initialize(BookingContext context) 
    { 
     context.Database.EnsureCreated(); 

     // Look for any students. 
     if (context.Customers.Any()) 
     { 
      return; // DB has been seeded 
     } 

     var customers = new Customer[] 
     { 
     new Customer{ID=201,FirstName="Joe",LastName="Gatto",Telephone="07580043213"}, 
     new Customer{ID=202,FirstName="Sal",LastName="Vulcano",Telephone="0758243454"}, 
     new Customer{ID=203,FirstName="James",LastName="Murray",Telephone="07580043290"}, 
     new Customer{ID=204,FirstName="Brian",LastName="Quinn",Telephone="075800432800"}, 
     new Customer{ID=205,FirstName="Joe",LastName="Gato",Telephone="0758004313"}, 
     new Customer{ID=206,FirstName="Sal",LastName="Vulcno",Telephone="075823454"}, 
     new Customer{ID=207,FirstName="James",LastName="Muray",Telephone="0750043290"}, 
     new Customer{ID=208,FirstName="Brian",LastName="Quin",Telephone="07500432800"} 

     }; 
     foreach (Customer s in customers) 
     { 
      context.Customers.Add(s); 
     } 
     context.SaveChanges(); 

内部例外:

{System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'Customer' when IDENTITY_INSERT is set to OFF. 
at System.Data.SqlClient.SqlConnection.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.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 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) 
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) 
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary`2 parameterValues, Boolean closeConnection) 
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues) 
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) 
ClientConnectionId:a4073037-3f12-4a01-9019-ab632c3325a0 
Error Number:544,State:1,Class:16} 
+1

InnerExceptionがあるはずです。投稿してください。また、 'Customer'クラスに、あなたがシードしていない必須フィールドがあるかどうかをチェックします。 –

+1

'try-catch'を使用して例外を取得し、' catch'にブレークポイントを設定し、例外の詳細を調べてエラーの詳細を取得します。完了したら、あなたに役立つより詳細な質問を更新することができます。 – bradbury9

答えて

2

Customer.Id列は、データベース内のID列としてマークされた(データベースは、それを生成するの世話をします)。このような列の値を明示的に設定することはできません。 Customer.IDプロパティの値を設定しています。そういうわけで、あなたはその例外を見ています。

SQLサーバーはレコードをテーブルに挿入する際にIDENTITY列に値を割り当てます。

次の解決策があります。

1 - データベースの列からIDENTITY制約を削除します。この方法であなたの現在のコードは正常に動作します。

二 - あなたは

var customers = new Customer[] 
{ 
    new Customer{FirstName="Joe",LastName="Gatto",Telephone="07580043213"}, 
    new Customer{FirstName="Sal",LastName="Vulcano",Telephone="0758243454"}, 
    new Customer{FirstName="James",LastName="Murray",Telephone="07580043290"} 
}; 
foreach (Customer s in customers) 
{ 
    context.Customers.Add(s); 
} 
context.SaveChanges(); 

三Customer.IDプロパティに値を割り当てられていない - あなたはCustomer.IDプロパティに値を割り当てるが、あなたは挿入する前に、テーブルの上にindentity_insertをONに設定する必要があります明示的なIDを持つ行を作成し、挿入後にOFFに設定します。

var customers = new Customer[] 
{ 
    new Customer{ID=201,FirstName="Joe",LastName="Gatto",Telephone="07580043213"}, 
    new Customer{ID=202,FirstName="Sal",LastName="Vulcano",Telephone="0758243454"}, 
    new Customer{ID=203,FirstName="James",LastName="Murray",Telephone="07580043290"} 
}; 

context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Customer ON") 

foreach (Customer s in customers) 
{ 
    context.Customers.Add(s); 
} 

context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Customer OFF") 

第一と第三のアプローチの問題は、あなたが次の顧客を挿入しようとしたときに、主キー違反エラーを取得しないように、顧客のために、最新の挿入IDを追跡する必要があります。

IDENTITY列の場合は、値を生成するためにSQL Serverに残すことをお勧めします。

0

あなたの内部例外で説明してい

{System.Data.SqlClient.SqlException:表内のID列に明示的な値を挿入できません。 IDENTITY_INSERTがOFFに設定されている場合は「Customer」です。

データベースにIDENTITY_INSERTをONにしたり、挿入されたデータからIDを削除してください

関連する問題