I have the following configuration class
internal class OrderItemConfiguration : EntityTypeConfiguration<OrderItem>
{
public OrderItemConfiguration()
{
ToTable("OrderItem");
HasRequired<Order>(m => m.Order)
.WithMany(q => q.OrderItems)
.HasForeignKey(m => m.OrderId)
.WillCascadeOnDelete();
}
}
But when I try to delete the order it throws the exception as
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.
Also I noted that the delete rule set to Cascade
in the foreign key.
When I delete in SSMS via query it deletes all.
My delete code in generic repository class is as follows
public virtual void Delete(TEntity entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Deleted)
{
dbEntityEntry.State = EntityState.Deleted;
}
else
{
DbSet.Attach(entity);
DbSet.Remove(entity);
}
}
public virtual void Delete(params object[] id)
{
var entity = GetById(id);
if (entity == null) return;
Delete(entity);
}