1

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);
    }
Jana
  • 137
  • 2
  • 11
  • Have a look at this maybe helful: http://stackoverflow.com/questions/34038286/cascade-delete-using-fluent-api – Salah Akbari Jan 02 '16 at 14:11
  • This configuration must be backed by cascading delete in the database foreign key. Also, it would be interesting to see the code that actually throws this error. – Gert Arnold Jan 02 '16 at 19:56
  • I followed the code first approach and as I said above the delete rule is Cascade for the foreign key. When I explicitly delete all the children it is deleting without any error. – Jana Jan 04 '16 at 02:50

1 Answers1

1

I finally solved it.

Refer the following thread to see mode detail Difference between DbSet.Remove and DbContext.Entry(entity).State = EntityState.Deleted

Community
  • 1
  • 1
Jana
  • 137
  • 2
  • 11