0

I'm learning EF, and have an error when trying to create my database. Introducing FOREIGN KEY constraint 'FK_dbo.ApplicationUserBuildings_dbo.Buildings_Building_BuildingID' on table 'ApplicationUserBuildings' 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 or index. See previous errors.

I understand what this error means, but I don't know exactly what do to in my code to get rid of if. I believe it's because there's a relationship between users and buildings and divisions and buildings. Here's my code. Users can have multiple buildings, Divisions can also have multiple buildings.

public class Division : Common.BaseModel
    {
        [Required]
        [Key]
        public int DivisionID { get; set; }

        [Required]
        public String Name { get; set; }

        public virtual ICollection<Building> Buildings { get; set; }

    }

public class Building : Common.BaseModel
    {
        [Required]
        [Key]
        public int BuildingID { get; set; }

        [Required]
        public String Name { get; set; }

        public int DivisionID { get; set; }

        public virtual Division Division { get; set; }

        public virtual ICollection<ApplicationUser> ApplicationUsers { get; set; }

    }

public class ApplicationUser 
    {

        public virtual ICollection<Building> Buildings { get; set; }

        public int DivisionID { get; set; }

        public virtual Division Divison { get; set; }
    }
user568551
  • 337
  • 3
  • 11
  • please can you update the question with Db Context ?? – RJ- Oct 20 '17 at 11:13
  • You have [circular references](https://stackoverflow.com/questions/17127351/introducing-foreign-key-constraint-may-cause-cycles-or-multiple-cascade-paths) in your model. Make DivisionID an `int?` or use fluent code to turn cascading deletes off. – Steve Greene Oct 20 '17 at 13:03
  • Don't have access to the code right now to post context. All users must have a division. Is this not possible in EF and I have to do that through code? What's the code for turning off Cascade deletes? I have tried that in fluent and couldn't get it – user568551 Oct 20 '17 at 14:43
  • 1
    `modelBuilder.Entity().HasRequired(c => c.Division) .WithMany().WillCascadeOnDelete(false);` – Steve Greene Oct 20 '17 at 17:49
  • Thank you. That took care of it. – user568551 Oct 24 '17 at 13:23

0 Answers0