【问题标题】:Entity framework parent -> child linking and foreign key constrain failed error实体框架父 -> 子链接和外键约束失败错误
【发布时间】:2016-06-30 20:50:30
【问题描述】:

我正在使用实体框架 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: '外键约束失败'"}

删除类别方法

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,
)

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

    • Aa 是的,基本上这个错误是需要的。但是,在某些情况下,此异常并不总是发生,并且数据库允许删除某些设备指向的类别。例如,当我启动应用程序并删除一个类别时,但如果在运行时我修改了设备类别字段然后尝试删除它,则会发生此异常。
    • 您是否有任何好的资源/教程来阅读有关处理实体框架SaveChanges() 方法异常的正确方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多