Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I am using database first approach . how can i use many to many relationships between two table and then how to insert data in database with many to many relationship between tables. I have to implement in my project but first i will practice it separately....Any helpful link and help will be appreciated
Posted
Comments
[no name] 24-Mar-14 11:27am    
I just want to know if I have two table say- student and course ....and there is many to many relationship between them then how can i save data in database in mvc

1 solution

First,

Your models should be something like below.

C#
public class Student
{
    public int StudentID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<AssignedCourseData> Courses { get; set; }
}

public class CourseViewModel
{
    public int CourseID { get; set; }
    public string CourseDescripcion { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}


And

Your create/update actions something like this

C#
[HttpPost]
    public ActionResult Create(Student student)
    {
        if (ModelState.IsValid)
        {
            var student = new Student { Name = student.Name };

            AddOrUpdateCourses(student, student.Courses);
            db.Student.Add(student);
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        return View(userProfileViewModel);
    }

    private void AddOrUpdateCourses(Student student, IEnumerable<AssignedCourseData> assignedCourses)
    {
        if (assignedCourses != null)
        {
            foreach (var assignedCourse in assignedCourses)
            {
                if (assignedCourse.Assigned)
                {
                    var course = new Course { CourseID = assignedCourse.CourseID };
                    db.Courses.Attach(course);
                    student.Courses.Add(course);
                }
            }
        }
    }


More can be found here...
http://codenodes.wordpress.com/2013/01/13/saving-many-to-many-data-in-mvc4-and-ef-4-1-code-first-part-1/[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900