onDelete action not working through ef6

Ashkan 1 Reputation point
2021-09-26T06:05:48.727+00:00

my WPF Application language is c# and used Entity Framework 6 and I have a SQLite database that one of tables has Foreignkey thet set it to Restrict for OnDelete Action

135208-image.png

Whenever I want to delete a record from parent table through sqlite expert, it does not allow deletion due to the child record in the related table, and this is absolutely correct,
But when I delete same record through the application, the record is deleted and this is incorrect: (beacuse has relation record on child table)

  var ashvam = db.AshkhasVam.Find(row.AshkhasVamId);  
                        db.AshkhasVam.Remove(ashvam);  
                        db.SaveChanges();  

Parent Table Class:

 public partial class AshkhasVam  
    {  
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]  
        public AshkhasVam()  
        {  
            this.PardakhtAghsat = new HashSet<PardakhtAghsat>();  
        }  
      
        public long AshkhasVamId { get; set; }  
        public long AshkhasID { get; set; }  
        public long VamtabID { get; set; }  
        public long VaziyattabID { get; set; }  
        public Nullable<System.DateTime> DateDaryaftMi { get; set; }  
        public string DateDaryaftSh { get; set; }  
        public long VamMablagh { get; set; }  
        public long Karmozd { get; set; }  
        public int TedAghsat { get; set; }  
        public long Ghest1Mablagh { get; set; }  
        public long SayerAghsatMablagh { get; set; }  
        public Nullable<System.DateTime> Ghest1DateMi { get; set; }  
        public string Ghest1DateSh { get; set; }  
      
        public virtual Ashkhas Ashkhas { get; set; }  
        public virtual Vaziyattab Vaziyattab { get; set; }  
        public virtual Vamtab Vamtab { get; set; }  
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]  
        public virtual ICollection<PardakhtAghsat> PardakhtAghsat { get; set; }  
    }  

Child table Class:

 public partial class PardakhtAghsat  
    {  
        public long PardakhtAghsatId { get; set; }  
        public long AshkhasVamID { get; set; }  
        public long Mablagh { get; set; }  
        public string DatePardakhtSh { get; set; }  
        public Nullable<System.DateTime> DatePardakhtMi { get; set; }  
        public int Sal { get; set; }  
        public int Mah { get; set; }  
      
        public virtual AshkhasVam AshkhasVam { get; set; }  
    }  
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,421 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,818 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 24,296 Reputation points Microsoft Vendor
    2021-09-28T08:04:49.76+00:00

    @Ashkan , based on my test, I reproduced your problem. I suggest that you could set Casccade delete in the dbcontext.

    Here is a sample code you could refer to.

    Main Method:

     static void Main(string[] args)  
            {  
                using (var ctx = new SchoolDbContext())  
                {  
                    School school = new School();  
                    school.SchoolName = "sch1";  
                    school.Address = "add1";  
      
                    var stud1 = new Student() { StuId = 1001, Name = "test1", School = school };  
                    var stud2 = new Student() { StuId = 1002, Name = "test3", School = school };  
                    var stud3 = new Student() { StuId = 1003, Name = "test3", School = school };  
                    school.students.Add(stud1);  
                    school.students.Add(stud2);  
                    school.students.Add(stud3);  
      
                    ctx.Students.Add(stud1);  
                    ctx.Students.Add(stud2);  
                    ctx.Students.Add(stud3);  
      
                    ctx.schools.Add(school);  
                    ctx.SaveChanges();  
                    var school1 = ctx.schools.Find(1);  
                    ctx.schools.Remove(school1);  
      
                    ctx.SaveChanges();  
                }  
            }  
    

    Model class:

     public  class School  
        {  
            public School()  
            {  
                this.students = new List<Student>();  
            }  
      
            [Key]  
            public int SchoolId { get; set; }  
      
            public string SchoolName { get; set; }  
      
            public string Address { get; set; }  
      
            public virtual ICollection<Student> students { get; set; }  
        }  
      
        public class Student  
        {  
            [Key]  
            public int StuId { get; set; }  
      
            public string Name { get; set; }  
      
            public School School { get; set; }  
      
        }  
    

    DbContext:

     public  class SchoolDbContext:DbContext  
        {  
            public SchoolDbContext() : base()  
            {  
      
            }  
      
            protected override void OnModelCreating(DbModelBuilder modelBuilder)  
            {  
                modelBuilder.Entity<Student>().HasOptional<School>(s => s.School).WithMany().WillCascadeOnDelete(false);  
            }  
            public DbSet<Student> Students { get; set; }  
            public DbSet<School> schools { get; set; }  
        }  
    

    We could use WillCascadeOnDelete(false) method to stop to delete the parent table when the child table is not deleted.

    If we execute the following code, I will get the following exception to stop to delete the data.

       var school1 = ctx.schools.Find(1);  
       ctx.schools.Remove(school1);  
          
       ctx.SaveChanges();  
    

    exception:

    135736-image.png


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments