如何在多对多mvc4中插入数据 [英] how to insert data in many to many relationship mvc4

查看:87
本文介绍了如何在多对多mvc4中插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在使用数据库第一种方法。我如何使用两个表之间的多对多关系,然后如何在数据库中插入数据与表之间的多对多关系。我必须在我的项目中实施,但首先我会单独练习....任何有用的链接和帮助将不胜感激

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

推荐答案

首先,



您的模型应如下所示。



First,

Your models should be something like below.

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

[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);
                }
            }
        }
    }





更多信息可以在这里找到.. 。

http://codenodes.wordpress.com/2013/01/13/saving-many-to-many-data-in-mvc4-and-ef-4-1- code-first-part-1 / [ ^ ]


这篇关于如何在多对多mvc4中插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆