实体框架多对多的关系是添加"末"项目之前添加关系 [英] Entity Framework Many To Many Relationship is adding "end" items BEFORE adding the relationship

查看:133
本文介绍了实体框架多对多的关系是添加"末"项目之前添加关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了使用普通学生和课程很简单的实体框架数据库的第一个项目的情况。

I have set up a very simple entity framework Database first project using the common Students and Courses scenario.


  • 学生可以有很多课程

  • 系统当然可以有很多学生

我已经建立了数据库中的关系和EF创造了一个很好的多对多导航项目这一点。

I have set up the relationship in the database and EF has created a nice Many to Many navigation item for this.

问题当我添加一门课程的学生,课程被重新添加到课程表,则关系被添加到数据库中,导致每个越来越多的重复的课程

The problem when I add a course to a student, the course gets RE-ADDED to the course table THEN the relationship gets added to the database, resulting in an every growing number of duplicated courses

这是我发疯,任何想法我可以做错了什么?

this is driving me nuts, any idea what I could be doing wrong?

我的一些code的....

Some of my code....

我创建了一个局部类通过一个实体上面生成的,这样我可以有一个复选框EditorTemplate,这将允许用户勾选过程中添加

I have created a Partial class over an above the entity generated one, so that I can have a EditorTemplate with a check box, this will allow the user to tick the course to add

public partial class Course
{
    public bool isSelected { get; set; }
}

public partial class Course
{
    public Course()
    {
        this.Students = new HashSet<Student>();
    }

    public int CourseId { get; set; }
    public string CourseName { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

编辑器模板课程

@model University.Models.Course

<div>
    @Html.CheckBoxFor(m => m.isSelected)
    @Html.DisplayFor(m => m.CourseName)


    @Html.HiddenFor(m => m.CourseName)
    @Html.HiddenFor(m =>m.CourseId)
</div>

在创建学生观

@model University.Models.CreateStudentViewModel            
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Student</legend>            
        <div class="editor-label">
            @Html.LabelFor(model => model.student.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.student.Name)
            @Html.ValidationMessageFor(model => model.student.Name)
        </div>    
        <div>        
            @Html.EditorFor(m=>m.courses)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

该视图模型为页

public class CreateStudentViewModel
{
    public Student student { get; set; }
    public ICollection<Course> courses { get; set; }
}

控制器

public ActionResult Create()
{
    CreateStudentViewModel vm = new CreateStudentViewModel();
    vm.courses = db.Courses.ToList();
    return View(vm);
} 
[HttpPost]
public ActionResult Create(CreateStudentViewModel model)
{
    if (ModelState.IsValid)
    {
        model.student.Courses = model.courses.Where(m => m.isSelected == true).ToList();
        db.Students.Add(model.student);
        db.SaveChanges();
        return RedirectToAction("Index");  
    }
    return View(model);
}

任何指着我正确的方向帮助将不胜AP preciated

Any help pointing me in the correct direction would be GREATLY appreciated

推荐答案

您必须的连接的所选课程的背景下在您的文章行动的 的添加学生之前的上下文。否则EF假定整个对象图 - 学生,包括所有课程 - 是的新的的和必须的插入的到数据库中。通过附加(=把课程纳入不变状态),再告诉你不想附加课程要插入新行,但只能创建新的关系EF学生和现有的课程:

You must attach the selected courses to the context in your post action before you add the student to the context. Otherwise EF assumes that the whole object graph - student including all courses - is new and must be inserted into the database. By attaching (=putting the courses into Unchanged state) you tell EF that you don't want the attached courses to be inserted as new rows but only create a relationship between the new student and the existing courses:

[HttpPost]
public ActionResult Create(CreateStudentViewModel model)
{
    if (ModelState.IsValid)
    {
        model.student.Courses =
            model.courses.Where(m => m.isSelected == true).ToList();

        foreach (var course in model.student.Courses)
            db.Courses.Attach(course);
        // now each course is in state Unchanged in the context

        db.Students.Add(model.student);
        // model.student is in state Added in the context
        // but the courses still have the state Unchanged.
        // Without the attach-loop above they would be in
        // state Added as well, which will create new courses
        // in the DB after SaveChanges

        db.SaveChanges();

        return RedirectToAction("Index");  
    }
    return View(model);
}

这篇关于实体框架多对多的关系是添加&QUOT;末&QUOT;项目之前添加关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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