简体   繁体   English

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

[英]Entity framework parent -> child linking and foreign key constrain failed error

I'm using entity framework 7 (core) and Sqlite database. 我正在使用实体框架7(核心)和Sqlite数据库。 Currently using comboBox to change entity category with this method: 当前使用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;
}

This function changes the category Id for the device just fine. 此功能改变为类别ID device就好了。 But is this correct way? 但这是正确的方法吗?

After linking and then later on while deleting this category I get an error from the Sqlite database: 链接之后,稍后再删除此category我从Sqlite数据库收到错误:

{"SQLite Error 19: 'FOREIGN KEY constraint failed'"} {“ SQLite错误19:'FOREIGN KEY约束失败'”]}

The delete category method 删除类别方法

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

EDIT Here are the structures of device and category : 编辑这是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,
)

Your SQLite table has a foreign key restriction ON DELETE RESTRICT . 您的SQLite表具有ON DELETE RESTRICT的外键限制。 This means if any row in Devices still points to the category you are trying to delete, the SQLite database will prevent this operation. 这意味着,如果“设备”中的任何行仍指向您尝试删除的类别,则SQLite数据库将阻止此操作。 To get around this, you can (1) explictly change all Devices to a different category or (2) change the ON DELETE behavior to something else, such as CASCADE or SET NULL . 要解决此问题,您可以(1)将所有设备显式更改为其他类别,或者(2)将ON DELETE行为更改为其他名称,例如CASCADESET NULL See https://www.sqlite.org/foreignkeys.html#fk_actions 参见https://www.sqlite.org/foreignkeys.html#fk_actions

If you have used EF to create your tables, then configure your model to use a different on delete behavior. 如果使用EF创建表,则将模型配置为使用其他on删除行为。 The default is restrict. 默认为限制。 See https://docs.efproject.net/en/latest/modeling/relationships.html#id2 . 请参阅https://docs.efproject.net/en/latest/modeling/relationships.html#id2 Example: 例:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架代码首先是多层父子外键 - Entity Framework code first multiple tier parent child foreign key 实体框架未将父ID映射为子表中的外键 - Entity Framework not mapping parent id as foreign key in child table 当Child具有WillCascadeOnDelete的外键时,实体框架无法删除父条目(false) - Entity Framework Cannot Delete Parent Entry When Child Has Foreign Key With WillCascadeOnDelete(false) 如何在ASP.NET MVC中使用实体框架在父表中创建外键并将其分配给子表 - How to create the foreign key in the parent table and assign it to the child table using entity framework in asp.net mvc 实体框架:如何在自引用父子关系上指定外键列的名称? - Entity Framework: How to specify the name of Foreign Key column on a self-referencing Parent-Child relationship? 实体框架生成新列,而不是链接提到的外键 - Entity Framework generates new column rather then linking the mentioned foreign key 实体框架代码优先将表链接在一起外键问题 - Entity Framework Code First Linking tables together foreign key issue 实体框架5添加具有其他外键关系的实体和子实体 - Entity Framework 5 add entity and child entities with other foreign key relationships 保存子实体不会使用实体框架保存外键 - Saving child entity is not saving the foreign key with entity framework 实体框架 - 将子类外键与父类主键相关联 - Entity Framework - relating subclass foreign key to parent class primary key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM