Reputation: 1089
Exception-Message:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
public int Delete(Foobar item)
{
using (var ctx = new DataContext())
{
ctx.Entry(item).State = EntityState.Deleted;
foreach (var singleFoo in item.Foos)
{
ctx.Entry(singleFoo ).State = EntityState.Deleted;
}
return ctx.SaveChanges();
}
}
I have cascade on delete on. If I delete the Foobar on my database, all Foos will delete, too - so Cascade delete works.
Why do I get this exception from EF 6?
EDIT:
If I use this code:
public int Delete(Foobar item) { using (var ctx = new DataContext()) { ctx.Set<Foobar>().Attach(item); ctx.Set<Foobar>().Remove(item); return ctx.SaveChanges(); } }
Everything works as I expect it. But I want to know why?
Upvotes: 0
Views: 419
Reputation: 14498
This problem will be resolved by not using EntityState
but just removing the entities:
ctx.Foobars.Remove(item);
The Remove()
method will also remove the child entities if cascade on delete is on because you're using it on the DbContext where the relations are defined (note you have to put it on in EF too, not only database!), EntityState.Deleted
will just mark the state of the entity as deleted in the objectContext and try to delete this one entity when you call SaveChanges()
. This will work if the relation between the entities is optional, then the foreign key property of the child entities will be set to null
when you save the changes to the database.
You should really only use EntityState
when you're working with detached entities, this way you can still make changes to the entities without having to fetch them from the database first, make the changes, and then save them again.
Upvotes: 2