1

I have this entity:

public class Course {
    public Course(){
        Postrequisites = new List<Course>();
        Prerequisites = new List<Course>();
    }
    public long Id { get; set; }
    public byte[] RowVersion { get; set; }
    // some other properties...
    public IList<Course> Postrequisites { get; set; }
    public IList<Course> Prerequisites { get; set; } 
}

which has a many-to-many self-referencing relationship. And here is my configuration:

public class CourseConfiguration : EntityTypeConfiguration<Course> {
    public CourseConfiguration() {
        // configurations for other properties...
        HasMany(t => t.Postrequisites)
            .WithMany(t => t.Prerequisites)
            .Map(t => {
                t.ToTable("CourseRequisites");
                t.MapLeftKey("PostrequisiteId");
                t.MapRightKey("PrerequisiteId");
            });
    }
}

When I try to delete an item with this method (see method Handle):

public class DeleteCommandHandlerBase {

    private readonly EntityContext _context;

    public DeleteCommandHandlerBase(EntityContext context) {
        _context = context;
    }

    protected virtual void Handle<TEntity>(long entityId) where TEntity : EntityBase, new() {
        var entity = _context.Set<TEntity>().Find(entityId);
        if (entity == null)
            throw new Exception(TextResources.ItemToDeleteNotFound);
        _context.Delete(entity); // see comment #1
        _context.SaveChanges();
    }
}

// comment #1
// _context.Delete is a custom method on my context which is:
public void Delete<TEntity>(TEntity entity) where TEntity : class {
    DbSet<TEntity> set = Set<TEntity>();
    if (Entry(entity).State == EntityState.Detached)
        set.Attach(entity);
    set.Remove(entity);
}

, I get this error:

An error occurred while updating the entries. See the inner exception for details.

Which the inner exception is:

An error occurred while updating the entries. See the inner exception for details.

Which the inner exception is:

The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.CourseRequisites_dbo.Courses_PostrequisiteId". The conflict occurred in database "MyDb", table "dbo.CourseRequisites", column 'PostrequisiteId'. The statement has been terminated.

Do you know what's going on?

amiry jd
  • 27,021
  • 30
  • 116
  • 215

1 Answers1

0

I am having the same error. Found this CASCADE Delete in many-to-many self-reference table

Unfortunatelly it is no solution. In essence it's a database problem. You first need to delete the relationship entries, before you can delete the entity itself.

But since we both have used Fluent API, we do not have access to the relationship table, at least I don't know how.

Community
  • 1
  • 1
Nils
  • 879
  • 1
  • 9
  • 19