我在我的项目中使用 WPF 和 EF6。
我有 2 个表 city(id_city, city_name) 和 person(id_person, name, id_city), id_city in person 表是一个 FK。
示例我有 2 个城市 C1 和 C2,1 个人 P1 住在城市 C1。然后我尝试使用此代码删除 C1
//I selected city C1 row in datagrid
city o = (city)cityDataGrid.SelectedCells[0].Item;
try
{
context.city.Remove(o);
context.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
它显然引发了 FK 异常。然后我尝试像这样删除 C2,尽管 C2 没有任何人,但它引发了 FK 异常。那么我该怎么做才能解决这个问题?
在我问了一个关于 的问题后DbContext
.Add()
,我了解到我应该像这样更改我的代码:
//I selected city C1 row in datagrid
city o = (city)cityDataGrid.SelectedCells[0].Item;
using (var context = new myDbContext())
{
try
{
context.city.Remove(o);
context.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
解释在这个问题Entity Framework Insert bug?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句