1

我一直在阅读http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/上的 Contoso 大学教程,特别是第 6 部分 ( http://www.asp. net/mvc/tutorials/getting-started-with-ef-using-mvc/updating-related-data-with-the-entity-framework-in-an-asp-net-mvc-application),其中添加了课程复选框到 Instructor Edit 视图,Instructor 和 Course 数据库表都会相应更新

不幸的是,本教程不包含如何创建新的讲师记录并插入到两个数据库表中。

任何人都可以提供指导如何修改编辑方法吗?

更新

我是实体框架的新手,但我是否正确地认为.Add会同时执行插入或更新?

如果是这样,我想知道我是否只需要改变这一点

var instructorToUpdate = db.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.Courses)
.Where(i => i.InstructorID == id)
.Single();

创建一个新的 id 而不是使用现有的 id?

更新结束

Http Post 操作方法

[HttpPost]
public ActionResult Edit(int id, FormCollection formCollection, string[] selectedCourses)
{
var instructorToUpdate = db.Instructors
    .Include(i => i.OfficeAssignment)
    .Include(i => i.Courses)
    .Where(i => i.InstructorID == id)
    .Single();
if (TryUpdateModel(instructorToUpdate, "", null, new string[] { "Courses" }))
{
    try
    {
        if (String.IsNullOrWhiteSpace(instructorToUpdate.OfficeAssignment.Location))
        {
            instructorToUpdate.OfficeAssignment = null;
        }

        UpdateInstructorCourses(selectedCourses, instructorToUpdate);

        db.Entry(instructorToUpdate).State = EntityState.Modified;
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    catch (DataException)
    {
        //Log the error (add a variable name after DataException)
        ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
   }
}
PopulateAssignedCourseData(instructorToUpdate);
return View(instructorToUpdate);
}

其他方法

private void UpdateInstructorCourses(string[] selectedCourses, Instructor instructorToUpdate)
{
if (selectedCourses == null)
{
    instructorToUpdate.Courses = new List<Course>();
    return;
}

var selectedCoursesHS = new HashSet<string>(selectedCourses);
var instructorCourses = new HashSet<int>
    (instructorToUpdate.Courses.Select(c => c.CourseID));
foreach (var course in db.Courses)
{
    if (selectedCoursesHS.Contains(course.CourseID.ToString()))
    {
        if (!instructorCourses.Contains(course.CourseID))
        {
            instructorToUpdate.Courses.Add(course);
        }
    }
    else
    {
        if (instructorCourses.Contains(course.CourseID))
        {
            instructorToUpdate.Courses.Remove(course);
        }
    }
}
}

...

private void PopulateAssignedCourseData(Instructor instructor)
{
var allCourses = db.Courses;
var instructorCourses = new HashSet<int>(instructor.Courses.Select(c => c.CourseID));
var viewModel = new List<AssignedCourseData>();
foreach (var course in allCourses)
{
    viewModel.Add(new AssignedCourseData
    {
        CourseID = course.CourseID,
        Title = course.Title,
        Assigned = instructorCourses.Contains(course.CourseID)
    });
}
ViewBag.Courses = viewModel;
}

编辑视图

@model ContosoUniversity.Models.Instructor

@{
ViewBag.Title = "Edit";
}

<h2>Edit</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>Instructor</legend>

    @Html.HiddenFor(model => model.PersonID)

    <div class="editor-label">
        @Html.LabelFor(model => model.LastName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.FirstMidName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.FirstMidName)
        @Html.ValidationMessageFor(model => model.FirstMidName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.HireDate)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.HireDate)
        @Html.ValidationMessageFor(model => model.HireDate)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.OfficeAssignment.Location)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.OfficeAssignment.Location)
        @Html.ValidationMessageFor(model => model.OfficeAssignment.Location)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.OfficeAssignment.Location)
    </div>
    <div class="editor-field">
        <table style="width: 100%">
            <tr>
                @{
                    int cnt = 0;
                    List<ContosoUniversity.ViewModels.AssignedCourseData> courses = ViewBag.Courses;

                    foreach (var course in courses) {
                        if (cnt++ % 3 == 0) {
                            @:  </tr> <tr> 
                        }
                        @: <td> 
                            <input type="checkbox" 
                                   name="selectedCourses" 
                                   value="@course.CourseID" 
                                   @(Html.Raw(course.Assigned ? "checked=\"checked\"" : "")) /> 
                            @course.CourseID @:&nbsp; @course.Title
                        @:</td>
                    }
                    @: </tr>
                }
        </table>
    </div>
    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>
4

1 回答 1

0

问题已经在这里回答了

我想我应该在问这个问题之前更努力地搜索!

于 2013-04-03T08:26:04.103 回答