实体框架父 - >子链接和外键约束失败错误

时间:2016-03-15 12:06:00

标签: c# sqlite foreign-key-relationship entity-framework-core

我正在使用实体框架7(核心)和Sqlite数据库。目前使用comboBox通过此方法更改实体类别:

/// <summary>
/// Changes the given device gategory.
/// </summary>
/// <param name="device"></param>
/// <param name="category"></param>
public bool ChangeCategory(Device device, Category category)
{
    if (device != null && category != null )
    {
        try
        {
            var selectedCategory = FxContext.Categories.SingleOrDefault(s => s.Name == category.Name);
            if (selectedCategory == null) return false;
            if (device.Category1 == selectedCategory) return true;

            device.Category1 = selectedCategory;
            device.Category = selectedCategory.Name;
            device.TimeCreated = DateTime.Now;
            return true;
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("Category change for device failed. Possible reason: database has multiple categories with same name.");
        }
    }
    return false;
}

此功能可以更改device的类别ID。但这是正确的方法吗?

链接后,稍后在删除此category时,我从Sqlite数据库收到错误:

  

{“SQLite错误19:'FOREIGN KEY约束失败'”}

删除类别方法

public bool RemoveCategory(Category category)
{
    if (category == null) return false;
    var itemForDeletion = FxContext.Categories
        .Where(d => d.CategoryId == category.CategoryId);
    FxContext.Categories.RemoveRange(itemForDeletion);
    return true;
}

修改 以下是devicecategory的结构:

CREATE TABLE "Category" (
    "CategoryId" INTEGER NOT NULL CONSTRAINT "PK_Category" PRIMARY KEY AUTOINCREMENT,
    "Description" TEXT,
    "HasErrors" INTEGER NOT NULL,
    "IsValid" INTEGER NOT NULL,
    "Name" TEXT
)

CREATE TABLE "Device" (
    "DeviceId" INTEGER NOT NULL CONSTRAINT "PK_Device" PRIMARY KEY AUTOINCREMENT,
    "Category" TEXT,
    "Category1CategoryId" INTEGER,
    CONSTRAINT "FK_Device_Category_Category1CategoryId" FOREIGN KEY ("Category1CategoryId") REFERENCES "Category" ("CategoryId") ON DELETE RESTRICT,
)

1 个答案:

答案 0 :(得分:1)

您的SQLite表具有外键限制ON DELETE RESTRICT。这意味着如果Devices中的任何行仍指向您尝试删除的类别,则SQLite数据库将阻止此操作。要解决此问题,您可以(1)明确地将所有设备更改为其他类别,或(2)将ON DELETE行为更改为其他内容,例如CASCADESET NULL。见https://www.sqlite.org/foreignkeys.html#fk_actions

如果您已使用EF创建表,则将模型配置为使用不同的删除行为。默认值为restrict。见https://docs.efproject.net/en/latest/modeling/relationships.html#id2。例如:

        modelBuilder.Entity<Post>()
            .HasOne(p => p.Blog)
            .WithMany(b => b.Posts)
            .OnDelete(DeleteBehavior.Cascade);