EF Core SQLite - Foreign Key nullable child insert (release)

.net-core c# ef-code-first entity-framework-core sqlite

Question

I have the following scenario:

public class ObjectA
{
    public ObjectA()
    {
        ObjectB = new HashSet<ObjectB>();
    }

    public Guid Id { get; set; }
    public string SomeFieldA { get; set; }

    public virtual ICollection<ObjectB> ObjectB { get; set; }
}
public class ObjectB
{
    public Guid Id { get; set; }
    public string SomeFieldB { get; set; }

    public Guid? IdObjectA { get; set; }
    public ObjectA ObjectA { get; set; }
}

public class DefaultContext : DbContext
{
    public DbSet<ObjectA> ObjectA { get; set; }
    public DbSet<ObjectB> ObjectB { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ObjectA>()
           .HasMany(b => b.ObjectB)
           .WithOne(b => b.ObjectA)
           .HasForeignKey(b => b.IdObjectA)
           .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Cascade);
    }
}

public class InsertClass
{
    public void Insert()
    {
        ObjectA objA = new ObjectA();
        objA.Id = Guid.NewGuid();
        objA.ObjectB = new List<ObjectB>();
        objA.ObjectB.Add(new ObjectB() { Id = Guid.NewGuid(), SomeFieldB = "SomeValue1" });
        objA.ObjectB.Add(new ObjectB() { Id = Guid.NewGuid(), SomeFieldB = "SomeValue2" });

        using (DefaultContext context = new DefaultContext())
        {
            context.Add(objA);
            context.SaveChanges();
        }
    }
}

The exception:

System.Data.SQLite.SQLiteException: constraint failed FOREIGN KEY

EF Core version 1.0.0 / 1.0.1

NOTE: This happen only in RELEASE mode, when you try it in DEBUG mode, it works fine. Someone have any idea if it is a bug, or am I missing something? Thanks!

1
0
10/6/2016 10:36:35 PM

Popular Answer

I have a feeling it might be related to the null FK. Have you considered trying a "default" (i.e. All zeros in GUID format) entry for the nullable. And I believe you might need to specify when the FK is changed (comparable logic in this case) then you would need to indicate to EFC that the Entity's state is Unchanged /Modified / Added or Deleted..

0
10/7/2016 9:50:23 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow