Sto usando l'entità framework 7 (core) e il database Sqlite. Attualmente usando comboBox per cambiare la categoria di entità con questo metodo:
/// <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;
}
Questa funzione cambia l'ID della categoria per il device
. Ma è questo il modo corretto?
Dopo il collegamento e successivamente durante l'eliminazione di questa category
ricevo un errore dal database Sqlite:
{"Errore SQLite 19:" Vincolo FOREIGN KEY non riuscito ""}
Il metodo di cancellazione della categoria
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 Ecco le strutture del device
e della 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,
)
La tabella SQLite ha una restrizione di chiave esterna ON DELETE RESTRICT
. Ciò significa che se qualsiasi riga in Dispositivi punta ancora alla categoria che stai tentando di eliminare, il database SQLite impedirà questa operazione. Per ovviare a questo, è possibile (1) modificare esplicitamente tutti i Dispositivi in una categoria diversa o (2) modificare il comportamento ON DELETE in qualcos'altro, come CASCADE
o SET NULL
. Vedi https://www.sqlite.org/foreignkeys.html#fk_actions
Se hai utilizzato EF per creare le tue tabelle, configura il tuo modello in modo che utilizzi un diverso comportamento di eliminazione. Il valore predefinito è limitato. Vedi https://docs.efproject.net/en/latest/modeling/relationships.html#id2 . Esempio:
modelBuilder.Entity<Post>()
.HasOne(p => p.Blog)
.WithMany(b => b.Posts)
.OnDelete(DeleteBehavior.Cascade);