简体   繁体   中英

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

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!

I have a feeling it might be related to the null FK. Have you considered trying a "default" (ie 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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM