@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:
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.