【发布时间】:2013-01-04 13:38:29
【问题描述】:
我有以下:
class City {
int id;
string Name;
ICollection<Person> Persons;
}
class Person {
int id;
string Name;
}
删除城市和所有相关人员的正确方法是什么? 可能我想避免外键约束并手动进行。 我试过了:
public bool Delete(int id // City Id)
{
City city = _db.Cities
.Include(c => c.Persons)
.First(c => c.Id == id);
if(city != null)
{
foreach (Person person in city.Persons)
{
_db.Persons.Remove(person);
}
_db.Cities.Remove(city);
_db.SaveChanges();
return true;
}
return false;
}
但是没有人或城市被从数据库中删除。
【问题讨论】:
-
你有没有得到一个城市?当你穿过时会发生什么?
-
调试时发生了什么?你甚至进入 foreach 了吗?
-
旁注:如果您使用
First(),城市不能为空。当城市不存在时,它会抛出异常。你能回答上面的问题吗? -
你可以看看。它可能会给你提示:stackoverflow.com/questions/2468027/…
标签: c# entity-framework ef-code-first entity-framework-5