title: One to one relationship entities of same type
body: <p>I'm very new in ASP.NetCore and EF Core.</p>
  
  <p>I'm having troubles to figure out how to handle this situation:</p>
  
  <p>I have a list of <strong>AvailableStudy</strong>, and every study has a list of <strong>AvailableStage</strong>. But also, a stage can depends on a previous stage (but is not mandatory), and the same happens with studies, a study can depends on a previous study. Here are the model classes:</p>
  
  <p><strong>BusinessObject:</strong></p>
  
  <pre><code> public class BusinessObject : IBusinessObject
      {
          #region Constructors
          public BusinessObject()
          {
              Id = Guid.NewGuid().ToString();
          }
  
          public BusinessObject(string name) :  this()
          {
              Name = name;
          }
          #endregion
  
          #region IBusinessObject implementation
          public string Id { get; set; }
          public string Name { get; set; }
  
          #endregion
      }
  </code></pre>
  
  <p><strong>AvailableStudy:</strong></p>
  
  <pre><code>   public class AvailableStudy : BusinessObject
      {
          #region Constructors
          public AvailableStudy() : base()
          {
              Stages = new List&lt;AvailableStage&gt;();
          }
  
          public AvailableStudy(string name) : base(name)
          {
              Stages = new List&lt;AvailableStage&gt;();
          }
          #endregion
  
  
          [ForeignKey("DependsOn")]
          public string DependsOnId { get; set; }
  
          #region Lazy-Load Properties
          public virtual List&lt;AvailableStage&gt; Stages { get; set; }
  
          public virtual AvailableStudy DependsOn { get; set; }
          #endregion
      }
  </code></pre>
  
  <p><strong>AvailableStage:</strong></p>
  
  <pre><code>public class AvailableStage : BusinessObject
      {
          #region Constructors
          public AvailableStage() : base()
          {
          }
  
          public AvailableStage(string name) : base(name)
          {
          }
  
          public AvailableStage(string name, AvailableStudy study) : base(name)
          {
              Study = study;
          }
          #endregion
  
  
          #region Properties
          [Required]
          public string StudyId { get; set; }
  
          public double Percentage { get; set; }
  
          public int Duration { get; set; }
  
          [ForeignKey("DependsOn")]
          public string DependsOnId { get; set; }
          #endregion
  
          #region Lazy-Load Properties
          public virtual AvailableStage DependsOn { get; set; }
  
          [ForeignKey("StudyId")]
          public virtual AvailableStudy Study { get; set; }
          #endregion        
      }
  </code></pre>
  
  <p>And finally, the OnModelCreating of my context class:</p>
  
  <pre><code>protected override void OnModelCreating(ModelBuilder modelBuilder)
          {
              base.OnModelCreating(modelBuilder);
  
              modelBuilder.Entity&lt;AvailableStudy&gt;().ToTable("AvailableStudies");
              modelBuilder.Entity&lt;AvailableStudy&gt;().HasMany(i =&gt; i.Stages).WithOne(c =&gt; c.Study);
             modelBuilder.Entity&lt;AvailableStudy&gt;().HasOne(i =&gt; i.DependsOn);
  
              modelBuilder.Entity&lt;AvailableStage&gt;().ToTable("AvailableStages");
              modelBuilder.Entity&lt;AvailableStage&gt;().HasOne(i =&gt; i.Study).WithMany(u =&gt; u.Stages);
              modelBuilder.Entity&lt;AvailableStage&gt;().HasOne(i =&gt; i.DependsOn);         
          }
  </code></pre>
  
  <p>I'm parsing a JSON file to generate a list of studies with their stages and dependencies.</p>
  
  <p><strong>A fragment of a JSON file</strong></p>
  
  <pre><code>{
    "Studies": [
      {
        "Name": "Concentrated",
        "DependsOn": "",
        "Stages": [
          {
            "Name": "IsConcentratedDone",
            "Percentage": 25,
            "Duration": 1
          },
          {
            "Name": "WasDescribed",
            "Percentage": 25,
            "Duration": 1
          },
          {
            "Name": "HasPhotos",
            "Percentage": 25,
            "Duration": 1
          },
          {
            "Name": "ReportFinished",
            "Percentage": 25,
            "Duration": 1
          }
        ]
      },
      {
        "Name": "AFT",
        "DependsOn": "Concentrated",
        "Stages": [
          {
            "Name": "IsMountDone",
            "Percentage": 25,
            "Duration": 1
          },
          {
            "Name": "SendedToIrradiation",
            "Percentage": 25,
            "Duration": 1
          },
          {
            "Name": "WasRecepted",
            "Percentage": 25,
            "Duration": 1
          },
          {
            "Name": "WasMeasured",
            "Percentage": 25,
            "Duration": 1
          }
        ]
      }
    ]
  }
  </code></pre>
  
  <p>Then, I add this studies to the proper DBSet in DBContext class and when I try to save changes throws an exception that says:</p>
  
  <p>SqlException: The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_AvailableStages_AvailableStages_DependsOnId". The conflict occurred in database "LateAndesSamples", table "dbo.AvailableStages", column 'Id'.
  The statement has been terminated.</p>
  
  <p>I'm really don't understand what's happening.</p>
  
  <p>Thansk for your help!</p>
  
  <p>The complete exception result is:</p>
  
  <pre><code>Microsoft.EntityFrameworkCore.DbUpdateException
    HResult=0x80131500
    Message=An error occurred while updating the entries. See the inner exception for details.
    Source=Microsoft.EntityFrameworkCore.Relational
    StackTrace:
     at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
     at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(DbContext _, ValueTuple`2 parameters)
     at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
     at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
     at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList`1 entries)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
     at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
     at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
     at LabManager.DataModel.Data.DbSeeder.CreateStudiesWithStages(ApplicationDbContext dbContext) in W:\LabManager\DataModel\src\Data\DbSeeder.cs:line 113
     at LabManager.DataModel.Data.DbSeeder.Seed(ApplicationDbContext dbContext, RoleManager`1 roleManager, UserManager`1 userManager, IHostingEnvironment env) in W:\LabManager\DataModel\src\Data\DbSeeder.cs:line 22
     at LabManagerWebPage.Extensions.ServiceExtensions.ConfigureDBContext(IApplicationBuilder app, IHostingEnvironment env) in W:\LabManager\LabManagerWebPage\Extensions\ServiceExtensions.cs:line 156
     at LabManagerWebPage.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env) in W:\LabManager\LabManagerWebPage\Startup.cs:line 107
  
  Inner Exception 1:
  SqlException: The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_AvailableStages_AvailableStages_DependsOnId". The conflict occurred in database "LateAndesSamples", table "dbo.AvailableStages", column 'Id'.
  The statement has been terminated.
  </code></pre>