This project has moved and is read-only. For the latest updates, please go here.

Effort fails to detect REFERENCE constraint

Nov 21, 2016 at 11:04 AM
So i have this model where i have the relation table connecting to two people
 public class People {
...
        public virtual ICollection<Relation> Relation { get; set; }
        public virtual ICollection<Relation> Relation2 { get; set; }
        public virtual ICollection<FollowUp> FollowUps { get; set; }
...
}
    public class Relation {
        [Key]
        [Column(Order = 0)]
        public int personRef1Id { get; set; }
        [Key]
        [Column(Order = 1)]
        public int personRef2Id { get; set; }
        public int RelationTypeRefId { get; set; }
        public virtual People person1 { get; set; }
        public virtual People person2 { get; set; }
        public virtual RelationType Relationtype { get; set; }
    }
with the override
  protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            modelBuilder.Entity<Relation>()
                .HasKey(i => new { i.personRef1Id, i.personRef2Id });

            modelBuilder.Entity<Relation>()
                .HasRequired(i => i.person1)
                .WithMany(i => i.Relation)
                .HasForeignKey(i => i.personRef1Id)
                .WillCascadeOnDelete(false); //the one

            modelBuilder.Entity<Relation>()
                .HasRequired(i => i.person2)
                .WithMany()
                .HasForeignKey(i => i.personRef2Id)
                .WillCascadeOnDelete(false); //the one
}
WillCascadeOnDelete is false since it will not work because of multiple cascade paths.

In any case, here is the problem.

When targeting the actual database if i try to delete a person that has relations i get:
{"The DELETE statement conflicted with the REFERENCE constraint \"FK_dbo.Relations_dbo.People_personRef1Id\". The conflict occurred in database \"prm.crmcontext\", table \"dbo.Relations\", column 'personRef1Id'.\r\nThe statement has been terminated."}
However when doing the same in my test (this particular one has 3 people and 1 relation between 2 of them)
context.Relations.Add(newRelation);
                context.SaveChanges();
                Assert.AreEqual(1, context.Relations.Count(), "Relations was not added properly");

                context.People.Remove(person1);
                context.SaveChanges();
                Assert.AreEqual(2, context.People.Count(), "People were not deleted properly");
                Assert.AreEqual(0, context.Relations.Count();
It works just fine.