2013-08-14 3 views
1

Я использую Entity Framework 5 и делаю обновление. Я получаю следующее исключение и с помощью SQL Profiler я не вижу SQL Выпущено:Как получить дополнительную информацию из EF DbUpdateException

catch (DbUpdateException ex) 
    { 
     return Request.CreateErrorResponse(HttpStatusCode.Conflict, ex); 
    } 

сообщение с этим говорит:

{System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.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_QuestionQuestionStatus". The conflict occurred in database "TestDb", table "dbo.QuestionStatus", column 'QuestionStatusId'. 
The statement has been terminated. 
    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) 
    at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) 
    at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) 
    at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) 
    at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) 
    at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues) 
    at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) 
    --- End of inner exception stack trace --- 
    at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) 
    at System.Data.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 TestDb.Models.Contexts.TestDbContext.SaveChanges() in c:\K\ST134 Aug 14\TestDb.Models\Contexts\TestDbContext.cs:line 101 
    at TestDb.Services.TestDbUowBase.Commit() in c:\K\ST135 Aug 15\TestDb.Services\TestDbUowBase.cs:line 48 
    at TestDb.Web.Controllers.ProblemController.PostProblem(Problem problem) in c:\K\ST135 Aug 15\WebUx\Controllers\ProblemController.cs:line 99} 

Обычно я могу найти ключ, за исключением, но в в этом случае я не вижу ничего полезного в списке исключений. Есть ли у кого-нибудь предложение о том, как я могу узнать больше?

ответ

8

Сообщение:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_QuestionQuestionStatus". The conflict occurred in database "TestDb", table "dbo.QuestionStatus", column 'QuestionStatusId'. 

звучит довольно точным я думаю. Проверьте, если ваш объект установил все (обязательные) внешние ключи в допустимое значение.

+0

Спасибо. Я потратил слишком много времени, глядя на детали, чтобы увидеть это. Я буду знать, где искать в следующий раз. Знаете ли вы, есть ли место в стеке исключений, откуда я мог извлечь эту информацию, чтобы я мог отправить ее в журнал. – Alan2

+0

без проблем, я научился читать исключения EF трудным путем :) Примите этот ответ, если он поможет решить вашу проблему. –

+0

Да, я согласен. еще раз спасибо – Alan2

Смежные вопросы