I have parent and child objects. In db, the relation is set to `ON DELETE CASCADE '.
The first Fluent api EF coding for a relationship:
this.HasMany(t => t.Children)
.WithOptional()
.HasForeignKey(d => d.ParentId)
.WillCascadeOnDelete();
Code for deleting an entity:
public virtual void Delete(Parent entity)
{
DbEntityEntry dbEntityEntry = dataContext.GetEntry(entity);
if (dbEntityEntry.State != EntityState.Deleted)
{
dbEntityEntry.State = EntityState.Deleted;
}
else
{
dbSet.Attach(entity);
dbSet.Remove(entity);
}
}
When I try to delete the parent, I get the following exception:
The operation failed: the relation cannot be changed because one or more properties of the foreign key are not NULL. When a change in relationship occurs, the corresponding property of the foreign key is set to zero. If the foreign key does not support null values, a new relationship must be defined, another nonzero value must be assigned to the foreign key property, or an object not associated with it must be deleted.
, EF ?
?
Delete:
if (entity.Children != null)
{
dataContext.Set<Child>().RemoveRange(entity.Children);
}
.
? EF/SQL Server ?