【发布时间】: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;
}
编辑
以下是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,
)
【问题讨论】:
标签: c# sqlite foreign-key-relationship entity-framework-core