ajr*_*ajr 3 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;
}
Run Code Online (Sandbox Code Playgroud)
此函数更改类别 IDdevice就好了。但这是正确的方法吗?
链接后,然后在删除它时,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;
}
Run Code Online (Sandbox Code Playgroud)
编辑
下面是结构device和category:
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,
)
Run Code Online (Sandbox Code Playgroud)
您的 SQLite 表有外键限制ON DELETE RESTRICT。这意味着如果 Devices 中的任何行仍然指向您尝试删除的类别,SQLite 数据库将阻止此操作。要解决此问题,您可以 (1) 将所有设备显式更改为不同的类别或 (2) 将 ON DELETE 行为更改为其他内容,例如CASCADE或SET 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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10932 次 |
| 最近记录: |