Tuesday, September 6, 2011

Entity Framework Code First Error: Could not create constraint

While using Entity Framework Code First you will run into an error similar to the one below if you create objects that have a circular reference.

Introducing FOREIGN KEY constraint 'File_Folder' on table 'Filess' 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.


The fix is pretty simple but not very intuitive.

Add the following line to your OnModelCreating override of your DbContext:

modelBuilder.Entity<File>().HasRequired(oo => oo.Folder).WithMany(oo => oo.Files).WillCascadeOnDelete(false);

So it looks something like this:

public class FilesystemDB : DbContext
{
 public DbSet<File> Files { get; set; }
 public DbSet<Folder> Folders { get; set; }
 
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
  modelBuilder.Entity<File>().HasRequired(oo => oo.Folder).WithMany(oo => oo.Files).WillCascadeOnDelete(false);
 }

}

For the best information on Entity Framework Code First read Morteza Manavi's blog.