entity-frameworkaspnetboilerplateasp.net-boilerplate

Repository insert with navigation property throws 'FOREIGN KEY constraint failed'


I'm using EF Core and sqlite. Given following 1-to-1 entities:

  public class Entity1:FullAuditedEntity<int>
  {
    public Entity2 Entity2 { get; set; }

    public string Name { get; set; }

  }

  public class Entity2: FullAuditedEntity<int>
  {

    public string Name { get; set; }       

    [ForeignKey("Entity1Id")]
    public Entity1 Entity1{ get; set; }
    public int Entity1Id { get; set; }
  }

and following insert logic:

    entity1.Entity2 = new Entity2();
    entity1= await entity1Repository.InsertAsync(entity1);//entity1Repository is of type IRepository<Entity1>

Code above throws:

Microsoft.EntityFrameworkCore.DbUpdateException : An error occurred while updating the entries. See the inner exception for details. ---- Microsoft.Data.Sqlite.SqliteException : SQLite Error 19: 'FOREIGN KEY constraint failed'. at ...

This approach doesn't work either, throws the same:

    var entity2 = new Entity2();
    entity1.Entity2 = entity2;
    entity2.Entity1 = entity1;
    entity1= await entity1Repository.InsertAsync(entity1);//entity1Repository 

What I'm doing wrong, what I'm missing? What is the correct way to create Entity1 and Entity2 with Entity2 property being set? Is it possible to create with Entity1 repo only?

Thanks in advance.

Update: Problem solved. In actual code entity2 has it's own reference on entity3, which is obvoiusly was throwing. It was the cause.


Solution

  • Like this?

    public class Entity1:FullAuditedEntity<int>
    {
       public Entity2 Entity2 { get; set; } = new Entity2();
    
       public string Name { get; set; }    
    }
    
    var entity1 = new Entity1();
    entity1 = await entity1Repository.InsertAsync(entity1);//entity1Repository
    

    Or do you want to clone? Check out: https://entityframeworkcore.com/knowledge-base/48873716/how-to-deep-clone-copy-in-ef-core