EF Core SQLite - 外鍵可空子插入(發布)

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

我有以下情況:

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();
        }
    }
}

例外:

System.Data.SQLite.SQLiteException:約束失敗FOREIGN KEY

EF Core版本1.0.0 / 1.0.1

注意:這僅在RELEASE模式下發生,當您在DEBUG模式下嘗試時,它可以正常工作。有人知道這是一個錯誤,還是我錯過了什麼?謝謝!

熱門答案

我覺得它可能與null FK有關。您是否考慮過嘗試為可空的“默認”(即GUID格式的全零)條目。而且我相信您可能需要指定何時更改FK(在這種情況下是可比較的邏輯)然後您需要向EFC指示實體的狀態是未更改/已修改/已添加或已刪除..



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow