2016-06-08 4 views
0

Я использую EF6 в своем приложении ASP.Net MVC. Для конкретной таблицы мое представление, обновление и удаление кода работает, но моя вставка выбрасывает DbUpdateException.Entity Framework 6 - Создание записи с идентификатором Autonumber ID DbUpdateException

System.Data.Entity.Infrastructure.DbUpdateException был необработанным кодом пользователя
HResult = -2146233087
Message = Невозможно определить действительный порядок для зависимых операций. Зависимости могут существовать из-за ограничений внешнего ключа, требований к модели или сохраненных в магазине значений.
Источник = EntityFramework
StackTrace:
на System.Data.Entity.Internal.InternalContext.SaveChanges() в SupportDiary.Models.SchedulerRequestService.Insert (запрос WRequestViewModel) в C: \ Projects \ SupportDiary \ SupportDiary \ Models \ SchedulerRequestService.vb: линия 92 на SupportDiary.Hubs.WRequestHub.Create (запрос WRequestViewModel) в C: \ Проекты \ SupportDiary \ SupportDiary \ концентраторы \ WRequestHub.vb: линия 37 на lambda_method (Закрытие, IHUB, Object []) в Microsoft.AspNet.SignalR.Hubs.HubDispatcher.Incoming (контекст IHubIncomingInvokerContext) InnerException: HResult = -2146233087 M essage = Невозможно определить действительный порядок для зависимых операций. Зависимости могут существовать из-за ограничений внешнего ключа, требований к модели или сохраненных в магазине значений. Источник = EntityFramework StackTrace: на System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.DependencyOrderingError (IEnumerable 1 remainder) at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ProduceCommands() at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func 1 FUNC, IDbExecutionStrategy executionStrategy, булева startLocalTransaction, булева releaseConnectionOnSuccess) в System.Data.Entity.Core .Objects.ObjectContext.SaveChangesToStore (SaveOptions варианты, IDbExecutionStrategy executionStrategy, булева startLocalTransaction) на System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute [TResult] (операции Func`1) на System.Data.Entity.Core.Objects. ObjectContext.SaveChangesInternal (опции SaveOptions, Boolean executeInExistingTransaction) в System.Data.Entity.Internal.InternalContext.SaveChanges() InnerException:

Это код для вставки и обновления ... как я уже сказал, работает Update.

 Public Overridable Function Insert(request As WRequestViewModel) As WRequestViewModel 

     Dim entity As New tWorkRequest() 

     entity.Start = request.Start 
     entity.[End] = request.[End] 
     entity.Title = request.Title 
     entity.Diary = request.Diary 
     entity.Team = request.Team 
     entity.WorkManagerID = request.WorkManagerID 
     entity.AssigneeID = request.AssigneeID 
     entity.ChangeRef = request.ChangeRef 
     entity.Description = request.Description 
     entity.ImpactedServers = request.ImpactedServers 
     entity.ImpactedServices = request.ImpactedServices 
     entity.IsBAU = request.IsBAU 
     entity.ProjectRef = request.ProjectRef 
     entity.Notes = request.Notes 
     entity.IsOOH = request.IsOOH 
     entity.IsAllDay = request.IsAllDay 
     entity.RecurrenceRule = request.RecurrenceRule 
     entity.RecurrenceID = request.RecurrenceID 
     entity.RecurrenceException = request.RecurrenceException 
     entity.StartTimezone = request.StartTimezone 
     entity.EndTimezone = request.EndTimezone 
     entity.RequestStatus = request.RequestStatus 

     Using de As New SupportDiaryEntities 

      de.tWorkRequests.Add(entity) 
      de.SaveChanges() 

      request.WRequestID = entity.WRequestID 

      Return request 

     End Using 

    End Function 

    Public Overridable Sub Update(request As WRequestViewModel) 

     Using de As New SupportDiaryEntities 

      Dim entity = de.tWorkRequests.FirstOrDefault(Function(r) r.WRequestID = request.WRequestID) 

      entity.Start = request.Start 
      entity.[End] = request.[End] 
      entity.Title = request.Title 
      entity.Diary = request.Diary 
      entity.Team = request.Team 
      entity.WorkManagerID = request.WorkManagerID 
      entity.AssigneeID = request.AssigneeID 
      entity.ChangeRef = request.ChangeRef 
      entity.Description = request.Description 
      entity.ImpactedServers = request.ImpactedServers 
      entity.ImpactedServices = request.ImpactedServices 
      entity.IsBAU = request.IsBAU 
      entity.ProjectRef = request.ProjectRef 
      entity.Notes = request.Notes 
      entity.IsOOH = request.IsOOH 
      entity.IsAllDay = request.IsAllDay 
      entity.RecurrenceRule = request.RecurrenceRule 
      entity.RecurrenceID = request.RecurrenceID 
      entity.RecurrenceException = request.RecurrenceException 
      entity.StartTimezone = request.StartTimezone 
      entity.EndTimezone = request.EndTimezone 
      entity.RequestStatus = request.RequestStatus 

      de.SaveChanges() 

     End Using 

    End Sub 

Если я просверлить в сущности в коде вставить его в поле Autonumber ID (WRequestId) установлен в 0

Я не уверен, как решить эту проблему ... поиск он-лайн дать подробности об ошибке в отношении DatabaseGeneratedOption.Identity, но это похоже на ошибку в EF4. Но я проверял свой файл edmx, и этот параметр установлен правильно во всех моих идентификационных полях для каждой таблицы.

Это автоматически генерируемый файл EF для рассматриваемой таблицы ...

'------------------------------------------------------------------------------ 
    ' <auto-generated> 
    '  This code was generated from a template. 
    ' 
    '  Manual changes to this file may cause unexpected behavior in your application. 
    '  Manual changes to this file will be overwritten if the code is regenerated. 
    ' </auto-generated> 
    '------------------------------------------------------------------------------ 

    Imports System 
    Imports System.Collections.Generic 

    Partial Public Class tWorkRequest 
     Public Property WRequestID As Integer 
     Public Property Title As String 
     Public Property Start As Date 
     Public Property [End] As Date 
     Public Property Diary As String 
     Public Property Team As String 
     Public Property WorkManagerID As Integer 
     Public Property AssigneeID As Integer 
     Public Property ChangeRef As String 
     Public Property Description As String 
     Public Property ImpactedServers As String 
     Public Property ImpactedServices As String 
     Public Property IsBAU As Boolean 
     Public Property ProjectRef As String 
     Public Property Notes As String 
     Public Property IsOOH As Boolean 
     Public Property IsAllDay As Boolean 
     Public Property RecurrenceRule As String 
     Public Property RecurrenceID As Nullable(Of Integer) 
     Public Property RecurrenceException As String 
     Public Property StartTimezone As String 
     Public Property EndTimezone As String 
     Public Property RequestStatus As Integer 

     Public Overridable Property tWorkRequests1 As ICollection(Of tWorkRequest) = New HashSet(Of tWorkRequest) 
     Public Overridable Property tWorkRequest1 As tWorkRequest 

    End Class 

Любые предложения кто-нибудь?

+1

Посмотрите на это решение http://stackoverflow.com/questions/14153208/unable-to-determine-a-valid-ordering-for-dependent-operations – ssanga

ответ

0

Ссылка, на которую указывала @ssanga, не имела принятого решения, но общий ответ был установлен, чтобы установить ID на -1. Я попробовал это, но получил другое исключение, которое указывало на другую проблему. Класс автогенерации EF для таблицы имел следующие строки ...

Public Overridable Property tWorkRequests1 As ICollection(Of tWorkRequest) = New HashSet(Of tWorkRequest) 
Public Overridable Property tWorkRequest1 As tWorkRequest 

Удаление этих строк и моего создания. Затем я снова вернулся к своему файлу edmx в Visual Studio и сгенерированной модели для базы данных, и эти строки снова не появлялись.

Не знаете, почему они были там в первую очередь.

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