0

A Template can have zero or many Document and zero or many MetaIndex. A Document can have zero or more Index, and a MetaIndex can also have zero or more Index:

enter image description here

This represent a potential cascade problem because deleting a Template will delete its Document (which is OK); deleting a Document will delete its Index, which is also OK. But when deleting a Template try to delete the MetaIndex (which will also delete Index) a problem will appear (a cycle).

I understand the problem. I think a way to solve it is specifying that when I delete a template it's documents and its document's indices get deleted, and also the meta-indices associated with the template. But that the metaindices do not cascade delete it's associated indices, so no cycles appear.

Searching here for a potential solution, I've tried this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<MetaIndex>().HasMany<Index>(m => m.IndicesEnteros).WithRequired().WillCascadeOnDelete(false);
}

But it's not working:

Introducing FOREIGN KEY constraint on table may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors.

Community
  • 1
  • 1
Erre Efe
  • 15,387
  • 10
  • 45
  • 77
  • Seems to me like you're trying to set a constraint when you specify WithRequired(), but then you set cascade to false. On the event the you delete a dependent element db would not update the other element and constraint would be violated. In order to solve this problem try enabling cascade. – Gustavo Apr 28 '15 at 18:20
  • @GustavoSuarez, cascade is precisely what I'm trying to remove. No matter if I use WithOptional() instead, behavior is the same. – Erre Efe Apr 28 '15 at 18:28

1 Answers1

0

Finally, after reading and re-reading the docs I was able to get it to work but understanding the order of the properties. I'm posting my own solution in case it could help others.

An Index has a required MetaIndex (because it it's non-nullable, if it were, then no cascade-delete were created). The next is specify how it is navigable (WithMany, the collection property on the MetaIndex class is Indices). Finally I need to specify the name of the foreign key field, which is (following the standards) MetaIndexID. Then I can specify that I don't need cascade delete. So the only way to delete Index with cascading is through document deletion (Which I wanted).

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    modelBuilder.Entity<Index>()
        .HasRequired(index => index.MetaIndex)
        .WithMany(metaIndex => metaIndex.Indices)
        .HasForeignKey(index => index.MetaIndexID)
        .WillCascadeOnDelete(false);

    base.OnModelCreating(modelBuilder);
}
Erre Efe
  • 15,387
  • 10
  • 45
  • 77