title: SQLite EF Core - 'FOREIGN KEY constraint failed'
body: <p>In my ASP.Net Core project I am getting this exception by starting, becuase I am initializing the database in runtime:</p>
  <blockquote>
  <p>fail: Microsoft.EntityFrameworkCore.Update[10000]</p>
  <p>An exception occurred in the database while saving changes for context type 'BlazorWeb.Server.Data.SQLiteTestDbContext'.<br />
  Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.</p>
  <p>Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 19: 'FOREIGN KEY constraint failed'.</p>
  <p>at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)<br />
  ....</p>
  </blockquote>
  <p>My models:</p>
  <pre class="lang-cs prettyprint-override"><code>public class ObjectModel : BaseEntity
  {
      [Key]
      public int Id { get; set; }
      public String Name { get; set; }
      public String PreviewImage { get; set; }
      public String  TagName { get; set; }
  
      // Foreign keys---
      public int TypeId { get; set; }
      public ObjectTypeModel TypeModel { get; set; }
      //---
  }
  
  public class ObjectTypeModel : BaseEntity
  {
      [Key]
      public int TypeId { get; set; }
      public String Name { get; set; }
      public String PreviewImage { get; set; }
      public String TagName { get; set; }
  
      public ICollection&lt;ObjectModel&gt; Objects { get; set; }
  }
  </code></pre>
  <p>My SQLite <code>OnModelCreating</code> method in the <code>DbContext</code>:</p>
  <pre><code>protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
      modelBuilder.Entity&lt;ObjectModel&gt;()
        .HasOne&lt;ObjectTypeModel&gt;(d =&gt; d.TypeModel)
        .WithMany(dm =&gt; dm.Objects)
        .HasForeignKey(dkey =&gt; dkey.TypeId);
  }
  </code></pre>
  <p>From the auto generated migration class:</p>
  <pre><code>            name: &quot;Objects&quot;,
              columns: table =&gt; new
              {
                  Id = table.Column&lt;int&gt;(nullable: false)
                      .Annotation(&quot;Sqlite:Autoincrement&quot;, true),
                  CreatedOn = table.Column&lt;DateTime&gt;(nullable: false),
                  ModifiedOn = table.Column&lt;DateTime&gt;(nullable: false),
                  Name = table.Column&lt;string&gt;(nullable: true),
                  PreviewImage = table.Column&lt;string&gt;(nullable: true),
                  TagName = table.Column&lt;string&gt;(nullable: true),
                  TypeId = table.Column&lt;int&gt;(nullable: false)
              },
              constraints: table =&gt;
              {
                  table.PrimaryKey(&quot;PK_Objects&quot;, x =&gt; x.Id);
                  table.ForeignKey(
                      name: &quot;FK_Objects_ObjectTypes_TypeId&quot;,
                      column: x =&gt; x.TypeId,
                      principalTable: &quot;ObjectTypes&quot;,
                      principalColumn: &quot;TypeId&quot;,
                      onDelete: ReferentialAction.Cascade);
              });
  </code></pre>
  <p>In my initialize method I am only filling it with some data and saving these to the context. But the database never receives these records and also the foreign key constraint exception occurs.</p>
  <p>Can anyone help me - am I doing something wrong?</p>
  <p><strong>EDIT</strong>
  I have found out that exception occurs after the SaveChangeAsync() method runtime.
  My overriden <code>SaveChangesAsyn()</code> method:</p>
  <pre class="lang-cs prettyprint-override"><code>     public Task&lt;int&gt; SaveChangesAsync()
       {
        var entries = ChangeTracker
              .Entries()
              .Where(e =&gt; e.Entity is BaseEntity &amp;&amp; (
                      e.State == EntityState.Added ||
                      e.State == EntityState.Modified));
  
              foreach (var entityEntry in entries)
              {
                  // overwrite `ModifiedOn` value with current date.
                  ((BaseEntity)entityEntry.Entity).ModifiedO=
                   DateTime.Now; 
  
                  // set `CreatedOn` to current date if its not already set. 
                  if (entityEntry.State == EntityState.Added)
                  {
                      ((BaseEntity)entityEntry.Entity).CreatedOn = DateTime.Now;
                  }
              }
              return base.SaveChangesAsync();
          }
  </code></pre>