2009-04-07 2 views
3

ОК, у меня есть и проблема с Entity Framework. У меня было это работает, но теперь добавлено несколько объектов в модель, и теперь я получая указанную выше ошибку. Для целей отладки я создал тестовую форму с элементом управления сеткой для заполнения из коллекции сущностей проектов. FYI, я использую GUID для своих первичных ключей. У меня есть только один бит кода:Исключение структуры Entity Framework: индекс был за пределами границ массива. "

Public Class TestForm 
Private Sub TestForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
    Me.ProjectBindingSource.DataSource = My.Application.Context.Projects 
End Sub 
End Class 

Вот деталь Исключение:

Внутренняя Исключение: { «Индекс находился вне границ массива.»} Источник: «System.Data.Enti ти «

System.Data.EntityCommandCompilationException было необработанное Message =» Произошла ошибка при подготовке определение команды. Смотрите внутреннее исключение для деталей « Source = "System.Data.Entity" StackTrace:. на System.Data.EntityClient.EntityCommandDefinition..ctor (DbProviderFactory storeProviderFactory, DbCommandTree commandTree) на System.Data.EntityClient.EntityProviderServices. CreateCommandDefinition (DbProviderFactory storeProviderFactory, DbCommandTree commandTree) на System.Data.EntityClient.EntityProviderServices.CreateDbCommandDefinition (DbProviderManifest providerManifest, DbCommandTree commandTree) на System.Data.Common.DbProviderServices.CreateCommandDefinition (DbCommandTree commandTree) в System.Data.Objects.Internal .ObjectQueryExecutionPlan.Prepare (контекст ObjectContext, дерево DbQueryCommandTree, тип elementType, MergeOption mergeOption, пробел) на System.Data.Objects.EntitySqlQueryState.GetExecutionPlan (Обнуляемые 1 forMergeOption) at System.Data.Objects.ObjectQuery 1.GetResults (Nullable 1 forMergeOption) at System.Data.Objects.ObjectQuery 1.GetIListSourceListInternal() в System.Data.Objects.ObjectQuery.System.ComponentModel.IListSource.GetList() в System.Windows. Forms.ListBindingHelper.GetList (список объектов) в System.Windows.Forms.ListBindingHelper.GetList (объект dataSource, String dataMember) в System.Windows.Forms.BindingSource.ResetList() в System.Windows.Forms.BindingSource. set_DataSource (значение объекта) в TestApp.TestForm.TestForm_Load (отправитель объекта, EventArgs e) в C: \ Users \ JoshPeltier.TFEARTH \ Documents \ Visual Studio 2008 \ Projects \ TestApp \ TestApp \ Forms \ TestForm.vb: строка 3 в System.EventHandler.Invoke (отправитель объекта, EventArg SE) на System.Windows.Forms.Form.OnLoad (EventArgs е) в System.Windows.Forms.Form.OnCreateControl() в System.Windows.Forms.Control.CreateControl (Boolean) fIgnoreVisible в System.Windows .Forms.Control.CreateControl() в System.Windows.Forms.Control.WmShowWindow (Message & м) в System.Windows.Forms.Control.WndProc (Message & м) на System.Windows.Forms.ScrollableControl. WndProc (Message & м) на System.Windows.Forms.ContainerControl.WndProc (Сообщение & м) в System.Windows.Forms.Form.WmShowWindow (Message & м) в System.Windows.Forms.Form.WndProc (Message & м) на System.Windows.Forms.Control.ControlNativeWindow.OnMessage (Сообщение & м) в System.Windows.Forms.Control.ControlNativeWindow.WndProc (Сообщение & m) в System.Windows.Forms.NativeWindow.DebuggableCallback (IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) в System.Windows.Forms.SafeNativeMethods.ShowWindow (HandleRef HWND, Int32 nCmdShow) на System.Windows.Forms.Control.SetVisibleCore (логическое значение) на System.Windows.Forms.Form.SetVisibleCore (логическое значение) на System.Windows.Forms.Control.set_Visible (логическое значение) на System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner (Int32 причине, ApplicationContext контекст) в System.Windows.Forms.Application.ThreadContext.RunMessageLoop (Int32 причине, ApplicationContext контекст) в System.Windows.Forms .Application.Run (контекст ApplicationContext) в Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun() в Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel() на Micros oft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run (String [] commandLine) at TestApp.My.MyApplication.Main (String [] Args) в 17d14f5c-a337-4978-8281-53493378c1071.vb: строка 81 в System.AppDomain ._nExecuteAssembly (сборка сборка, String [] арг) в System.AppDomain.ExecuteAssembly (String assemblyFile, Evidence assemblySecurity, String [] арг) на Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() в System.Threading.ThreadHelper .ThreadStart_Context (состояние объекта) на System.Threading.ExecutionContext.Run (ExecutionContext ExecutionContext, ContextCallback обратного вызова, состояние объекта) на System.Threading.ThreadHelper.ThreadStart() InnerException: System.IndexOutOfRangeException Сообщение = «Индекс находился за пределами массива». Source = "System.Data.Entity" StackTrace: на System.Data.Mapping.ViewGeneration.Structures.CellQuery.CreateFieldAlignedCellQueries (CellQuery otherQuery, MemberPathMapBase projectedSlotMap, CellQuery & newMainQuery, CellQuery & newOtherQuery) в System.Data.Mapping .ViewGeneration.CellNormalizer.AlignFields (IEnumerable 1 cells, MemberPathMapBase projectedSlotMap, ViewTarget viewTarget) at System.Data.Mapping.ViewGeneration.CellNormalizer.CreateLeftCellWrappers(IEnumerable 1 extentCells, ViewTarget viewTarget) в System.Data.Mapping.ViewGeneration.CellNormalizer..ctor (EntitySetBase степени, IEnumerable 1 extentCells, SchemaContext schemaContext, CqlIdentifiers identifiers, ConfigViewGenerator config, MemberDomainMap queryDomainMap, MemberDomainMap updateDomainMap, StorageEntityContainerMapping entityContainerMapping, MetadataWorkspace workspace) at System.Data.Mapping.ViewGeneration.ViewGenerator.GetCellNormalizer(EntitySetBase extent, SchemaContext schemaContext, CqlIdentifiers identifiers) at System.Data.Mapping.ViewGeneration.ViewGenerator.GenerateViewsForExtent(SchemaContext schemaContext, EntitySetBase extent, CqlIdentifiers identifiers, KeyToListMap 2 просмотров) на System.Data.Mapping.ViewGeneration.ViewGenerator. GenerateViewsForSchemaContext (SchemaContext schemaContext, идентификаторы CqlIdentifiers, KeyToListMap 2 views) at System.Data.Mapping.ViewGeneration.ViewGenerator.GenerateAllViews(KeyToListMap 2 просмотра, CqlIdentifiers iden мителей) в System.Data.Mapping.ViewGeneration.ViewGenerator.GenerateViewsForSchemaCells (Список 1 cells, MetadataWorkspace workSpace, ConfigViewGenerator config, CqlIdentifiers identifiers, StorageEntityContainerMapping containerMapping) at System.Data.Mapping.ViewGeneration.ViewGenerator.GenerateViewsForSchema(StorageEntityContainerMapping containerMapping, MetadataWorkspace workSpace, ConfigViewGenerator config) at System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGenerateViews(EntityContainer container, Dictionary 2 resultDictionary) в System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGetGeneratedViews (EntityContainer контейнер) в System.Data.Common.Utils.Memoizer 2.<>c__DisplayClass2.<Evaluate>b__0() at System.Data.Common.Utils.Memoizer 2.Result.GetValue() на System.Data.Common.Utils.Memoizer 2.Evaluate(TArg arg) at System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.GetGeneratedView(EntitySetBase extent, MetadataWorkspace workspace, StorageMappingItemCollection storageMappingItemCollection) at System.Data.Metadata.Edm.MetadataWorkspace.GetGeneratedView(EntitySetBase extent) at System.Data.Query.PlanCompiler.PreProcessor.ExpandView(Node node, ScanTableOp scanTableOp, IsOfOp& typeFilter) at System.Data.Query.PlanCompiler.PreProcessor.ProcessScanTable(Node scanTableNode, ScanTableOp scanTableOp, IsOfOp& typeFilter) at System.Data.Query.PlanCompiler.PreProcessor.Visit(ScanTableOp op, Node n) at System.Data.Query.InternalTrees.ScanTableOp.Accept[TResultType](BasicOpVisitorOfT 1 в, узел п) на System.Data.Query.InternalTrees.BasicOpVisitorOfT 1.VisitNode(Node n) at System.Data.Query.PlanCompiler.PreProcessor.VisitChildren(Node n) at System.Data.Query.PlanCompiler.PreProcessor.VisitRelOpDefault(RelOp op, Node n) at System.Data.Query.PlanCompiler.PreProcessor.Visit(ProjectOp op, Node n) at System.Data.Query.InternalTrees.ProjectOp.Accept[TResultType](BasicOpVisitorOfT 1 в, узел п) в System.Data.Query .InternalTrees.BasicOpVisitorOfT 1.VisitNode(Node n) at System.Data.Query.PlanCompiler.PreProcessor.VisitChildren(Node n) at System.Data.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n) at System.Data.Query.InternalTrees.BasicOpVisitorOfNode.VisitPhysicalOpDefault(PhysicalOp op, Node n) at System.Data.Query.InternalTrees.BasicOpVisitorOfT 1.Visit (PhysicalProjectOp op, Node n) в System.Data.Query.InternalTrees.PhysicalProjectOp.Accept [TResultType] (BasicOpVisitorOfT 1 v, Node n) at System.Data.Query.InternalTrees.BasicOpVisitorOfT 1.VisitNode (Узел п) на System.Data.Query.PlanCompiler.PreProcessor.Process() в System.Data.Query.PlanCompiler.PreProcessor.Process (PlanCompiler planCompilerState, StructuredTypeInfo & TypeInfo) в System.Data. Query.PlanCompiler.PlanCompiler.Compile (Список entitySets) в System.Data.Query.PlanCompiler.PlanCompiler.Compile (DbCommandTree Ctree, Список entitySets) в System.Data.EntityClient.EntityCommandDefinition ..т е р (DbProviderFactory storeProviderFactory, DbCommandTree commandTree) InnerException:

Любые идеи?

+0

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

ответ

1

Я только что это случилось со мной.

Проблема оказалась связью с конечными ключами, которые не были частью первичного ключа для этого объекта!

Например, глубоко в моей EDMX-я имел эту ассоциацию:

<AssociationSetMapping Name="Table1Table2" TypeName="MyModel.Table1Table2" StoreEntitySet="Table2"> 
    <EndProperty Name="Table1"> 
     <ScalarProperty Name="Table1Key" ColumnName="Table1Key" /></EndProperty> 
    <EndProperty Name="Table2"> 
     <ScalarProperty Name="Table2Key" ColumnName="Table2Key" /> 
     <ScalarProperty Name="Table2OtherColumn" ColumnName="Table2OtherColumn" /> 
</EndProperty></AssociationSetMapping> 

и определение Table2 выглядит следующим образом:

<EntityType Name="Table2"> 
    <Key> 
     <PropertyRef Name="Table2Key" /> 
    </Key> 
    <Property Name="Table2Key" Type="int" Nullable="false" /> 
    <Property Name="Table2OtherColumn" Type="int" Nullable="false" /> 
    ...other properties... 
</EntityType> 

Обратите внимание, что Table2OtherColumn находится в EndProperty, но не является частью фактического ключа. Исправлена ​​проблема с удалением его из EndProperty.

Обратите внимание, что Entity Framework 4 (Visual Studio 2010) может обнаружить эту проблему во время компиляции. Таким образом, если у вас возникли серьезные проблемы с отслеживанием того, какая таблица/свойство вызывает это, просто загрузите проект в VS 2010 Express (после его поддержки!) И попытайтесь скомпилировать.

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