title: Entity Framework throws exception: index was outside the bounds of the array
body: <p>I've been struggling with having a foreign key to' AspNetUsers' table a lot.</p>
  
  <p>I renamed the table to <code>Users</code> in my SQL Server database just to clarify. I have a foreign key in my <code>Tutorial</code> table to the <code>Users</code> table. Here's my EF model class for <code>Tutorial</code> table: </p>
  
  <pre><code>public class Tutorial
  {
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
      public int TutorialID { get; set; }
  
      [Required]
      public string TutorialTitle { get; set; }
  
      [Required]
      public string Description { get; set; }
  
      [Required]
      public string TutorialUrl { get; set; }
  
      public string TutorialContent { get; set; }
      public string UserId { get; set; }
  
      public virtual AppUser User { get; set; } // this on is IdentityUser actually
  
      public DateTime? Published { get; set; }
      public bool HasBeenAcceptedForPublish { get; set; }
      public string AdminMessageForNotPublishing { get; set; }
  
      [Required]
      public virtual TutorialStatus TutorialStatus { get; set; }
  }
  </code></pre>
  
  <p>So after I updated database, when every I save new <code>Tutorial</code> to EF, it throws an error: </p>
  
  <blockquote>
    <p>Index was outside the bounds of the array</p>
  </blockquote>
  
  <p>I'm guessing that there is something wrong with foreign key to the <code>Users</code> table. It's the <code>AppUser</code> object that is related to. I'm gonna throw here script for <code>Tutorial</code> table if anyone could make sense, what is throwing that exception/error.</p>
  
  <pre><code>CREATE TABLE [dbo].[Tutorials] 
  (
      [TutorialID] INT IDENTITY (1, 1) NOT NULL,
      [TutorialTitle] NVARCHAR (MAX) NOT NULL,
      [Description] NVARCHAR (MAX) NOT NULL,
      [TutorialUrl] NVARCHAR (MAX) NOT NULL,
      [TutorialContent] NVARCHAR (MAX) NULL,
      [Published] DATETIME NULL,
      [HasBeenAcceptedForPublish] BIT NOT NULL,
      [AdminMessageForNotPublishing] NVARCHAR (MAX) NULL,
      [TutorialStatus_TutorialStatusID] INT NOT NULL,
      [UserId] NVARCHAR (128) NULL,
  
      CONSTRAINT [PK_dbo.Tutorials] 
         PRIMARY KEY CLUSTERED ([TutorialID] ASC),
      CONSTRAINT [FK_dbo.Tutorials_dbo.TutorialStatus_TutorialStatusID] 
         FOREIGN KEY ([TutorialStatus_TutorialStatusID]) 
         REFERENCES [dbo].[TutorialStatus] ([TutorialStatusID]) 
         ON DELETE CASCADE,
      CONSTRAINT [FK_dbo.Tutorials_dbo.Users_Id] 
         FOREIGN KEY ([UserId]) 
         REFERENCES [dbo].[Users] ([Id])
  );
  GO
  
  CREATE NONCLUSTERED INDEX [IX_TutorialStatus_TutorialStatusID]
  ON [dbo].[Tutorials]([TutorialStatus_TutorialStatusID] ASC);
  GO
  
  CREATE NONCLUSTERED INDEX [IX_UserId]
  ON [dbo].[Tutorials]([UserId] ASC); 
  </code></pre>
  
  <p>UPDATE:</p>
  
  <p>Here is the code which creates the new tutorial and tries to save it to database.</p>
  
  <pre><code>public Tutorial CreateNewTutorial(string TutorialTitle, string Description, string content, AppUser user, out bool success)
  {
      try
      {
          string tutorialurl = null;
          tutorialurl = TutorialTitle.Replace(" ", "-");
          Tutorial tutorial = new Tutorial();
  
          TutorialStatus status = new TutorialStatus();
          status.ViewCount = 1;
          status.ReputationPoints = 0;
          status.FavouritedCount = 0;
  
          context.TutorialStatus.Add(status);
          context.SaveChanges();
  
          tutorial.TutorialTitle = TutorialTitle;
          tutorial.Description = Description;
          tutorial.TutorialUrl = tutorialurl;
          tutorial.User = user;
          tutorial.UserId = user.Id;
          tutorial.Published = null;
          //tutorial.TutorialStatusID = status.TutorialStatusID;
          tutorial.TutorialContent = content;
  
          context.Tutorials.Add(tutorial);
          context.SaveChanges();
  
          success = true;
          return tutorial;
      }
      catch
      {
          success = false;
          return null;
      }
  }
  </code></pre>
  
  <p>UPDATE 2:
  Here's the stacktrace:</p>
  
  <pre><code>at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.FindRelationshipSet(ObjectContext context, EntitySet entitySet, EdmType&amp; relationshipType, RelationshipSet&amp; relationshipSet)
  at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AttachContext(ObjectContext context, EntitySet entitySet, MergeOption mergeOption)
  at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AttachContext(ObjectContext context, MergeOption mergeOption)
  at System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.CreateRelatedEnd[TSourceEntity,TTargetEntity](RelationshipNavigation navigation, RelationshipMultiplicity sourceRoleMultiplicity, RelationshipMultiplicity targetRoleMultiplicity, RelatedEnd existingRelatedEnd)
  at System.Data.Entity.Core.Objects.DataClasses.RelationshipFixer`2.System.Data.Entity.Core.Objects.DataClasses.IRelationshipFixer.CreateSourceEnd(RelationshipNavigation navigation, RelationshipManager relationshipManager)
  at System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.GetRelatedEnd(RelationshipNavigation navigation, IRelationshipFixer relationshipFixer)
  at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.GetOtherEndOfRelationship(IEntityWrapper wrappedEntity)
  at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
  at System.Data.Entity.Core.Objects.DataClasses.EntityReference`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach)
  at System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach)
  at System.Data.Entity.Core.Objects.ObjectContext.AddObject(String entitySetName, Object entity)
  at System.Data.Entity.Internal.Linq.InternalSet`1.&lt;&gt;c__DisplayClassd.&lt;Add&gt;b__c()
  at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
  at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
  at System.Data.Entity.DbSet`1.Add(TEntity entity)
  at TutorialNetworkDomain.EFRepositories.EFHomeRepository.CreateNewTutorial(String TutorialTitle, String Description, String content, AppUser user, Boolean&amp; success) in C:\\Users\\Jon\\Source\\Workspaces\\TutorialNetwork\\TutorialNetwork\\TutorialNetworkDomain\\EFRepositories\\EFHomeRepository.cs:line 362
  </code></pre>