0

I am getting the following exception:

enter image description here

I have gone through many posts here, here and here. But no post suggests proper solution to the problem. I want to know how can this situation be tackled practically.

My Models and Contexts are as follows:

public class Context : DbContext
    {
        public Context() : base("DefaultConnection")
        {
        }
        public DbSet<Student> Students { get; set; }
        public DbSet<Course> Courses { get; set; }
        public DbSet<Staff> Staffs { get; set; }
    }

public class Student
    {
        public int StudentId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [Required]
        public virtual Course Course { get; set; }
        [Required]
        public virtual Staff Staff { get; set; }

    }


 public class Staff
       {
           public int StaffId { get; set; }
           public string Name { get; set; }
           public string  Contact { get; set; }
       }


public class Course
    {
        public int CourseId { get; set; }
        public string CourseName { get; set; }
        [Required]
        public virtual Staff Staff { get; set; }
    }

I am getting this exception on the line :

 context.Students.Add(student);

of the following code:

 public void AddStudent()
        {
            Student student = new Student();
            student.FirstName = "Bruce";
            student.LastName = "Wayne";
            student.Course = new Course();
            student.Course.CourseName = "CSE";
            student.Course.Staff = new Staff();
            student.Course.Staff.Name = "Albert";
            student.Course.Staff.Contact = "1234567890";
            context.Students.Add(student);
            context.Courses.Add(student.Course);
            context.SaveChanges();
            Console.WriteLine("Student , Course, Staff Added");
        }
Community
  • 1
  • 1
Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79

2 Answers2

0

I had asked this question some time back. This should help you out.

EF Code First giving problems in foreign keys

Reference reading here

http://weblogs.asp.net/manavi/archive/2011/05/01/associations-in-ef-4-1-code-first-part-5-one-to-one-foreign-key-associations.aspx

The main part to look for in the article is "What's a Multiple Cascade Path Anyway?"

To solve the problem practically you need to identify which path do you want the cascade delete to be turned on. For e.g. If the a staff gets deleted does the course also get deleted or does it remain ?

Community
  • 1
  • 1
ashutosh raina
  • 9,228
  • 12
  • 44
  • 80
0

Disabling cascading deletes for that entity should solve your issue. If you want a cascading delete for this set of entities, do it manually. It can't be done automatically because when there's a cycle there's no way to determine when to stop.

Community
  • 1
  • 1
Allon Guralnek
  • 15,813
  • 6
  • 60
  • 93