My code worked fine until I added the WillCascadeOnDelete(true).
Exception: InvalidOperationException – The database creation succeeded, but the creation of the database objects did not. See inner exception for more details.
Inner Exception: System.Data.SqlServerCe.SqlCeException – The referential relationship will result in a cyclical reference that is not allowed. [ Constraint name = User_AdministratorOf_Target ]
Minimal reproduction (In a new MVC3 Web app project):
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
public class User
{
[Key]
public string UserName { get; set; }
public virtual ICollection<Document> Documents { get; set; }
public virtual ICollection<Document> AdministratorOf { get; set; }
}
public class Document
{
public int Id { get; set; }
public User Owner { get; set; }
public ICollection<User> Administrators{ get; set; }
}
public class EntityMappingContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Document> Documents { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(x => x.AdministratorOf)
.WithMany(x => x.Administrators)
.Map(x =>
{
x.MapLeftKey("UserName");
x.MapRightKey("Document");
x.ToTable("DocumentAdministrators");
});
modelBuilder.Entity<Document>()
.HasRequired(x => x.Owner)
.WithMany(x => x.Documents)
.WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
}
Also have to add the SQL connection string to web.config under connectionStrings of course:
<add name="EntityMappingContext" connectionString="Data Source=|DataDirectory|Error.sdf" providerName="System.Data.SqlServerCe.4.0"/>
How does enabling cascade on delete create a cyclic relationship when the one-to-many relationship already existed? Is it saying that there’s a cycle in the cascading delete? How, when the only cascade I’ve specified is User -> Document? How do I fix it? Thanks!
The cascade delete error is not necessarily due to cyclical relationship, but by having multiple references to the same table in a delete tree see this post.
The trigger is Delete:
By deleting a user, it’s triggering the deletion of the many to many table twice, giving you the error. It may be better to just have the deletion of all documents belonging to the owner in your business logic.