Reputation: 633
I've the following:
class City {
int id;
string Name;
ICollection<Person> Persons;
}
class Person {
int id;
string Name;
}
Which is the correct way to delete a City and all related Person? Possibly I'd like to avoid foreign key constraint and do it manually. I've tried:
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;
}
But no person or city are being removed from the database.
Upvotes: 4
Views: 409
Reputation: 2075
Your code seems correct...
You could also try using below code to delete entities:
foreach (Person person in city.Persons)
{
_db.Persons.Entry(person).State = EntityState.Deleted;
}
_db.Cities.Entry(city).State = EntityState.Deleted;
_db.SaveChanges();
One more thing...
If you use First
to get the City
then the if
statement will always be true
since First
expects to have a match and it throws an InvalidOperationException
when the source sequence is empty.
Looking at your code I can see that the method returns true
if there was a match by id
and the deletion was performed, if there was no match it returns false
. For city
to be null
you should use FirstOrDefault
, it returns the default value of the type handled if the source sequence is empty, which in your case would be null
.
Upvotes: 1