2

私はこのすべてで本当に新しいです。私は現在、ASP.NET Web サイトでチュートリアル「Getting Started with EF using MVC」を読んでいます: (第 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-応用

チュートリアルの「インストラクター編集ページにコースの割り当てを追加する」というタイトルの部分で、著者はインストラクターページでコースを編集する方法について書いています。

    public ActionResult Edit(int id)
    {
        Instructor instructor = db.Instructors
            .Include(i => i.OfficeAssignment)
            .Include(i => i.Courses)
            .Where(i => i.InstructorID == id)
            .Single();
        PopulateAssignedCourseData(instructor);
        return View(instructor);
    }

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

アクションメソッドの削除と作成を達成するために(作成者と同じ概念を)使用する方法を教えてください。または、上記のチュートリアルと同様に、MVC での EF との多対多の関係、特にコントローラーを作成し、多対多の関連データを表示する方法について、役立つチュートリアル/サイトに案内していただければ幸いです。私はこれの初心者ですが、まだ作業を完了する必要があるため、使用される概念が一致すると非常に役立ちます。

よろしくお願いします!

4

2 に答える 2

1

通常、作成と削除はもう少し簡単です。基本的な構造だけを概説しました。エントリ作成ページのコントローラは次のとおりです。

public ViewResult CreateInstructor()
        {
            return View();
        }

作成フォームを生成するには、スキャフォールディングを使用できます ([ビュー] を右クリックして [ビューの追加...] を選択し、適切なモデルとページ タイプを選択します)。このページのポストバックは [HttpPost] 属性を持つコントローラーによって処理され、フォーム上のデータがコントローラー メソッドに渡されたオブジェクトにバインドされ、これが DBContext の Add() メソッドに渡され、最後に実行されます。データベースに実際にヒットする SaveChanges() メソッド:

 [HttpPost]
        public ActionResult CreateInstructor(Instructor instructor)
        {
db.Instructors.Add(instructor);
db.Instructors.SaveChanges();
 return View(); //There will be some other logic here typically such as redirecting on a successful creation or showing specific validation issues with the object .

}

削除は DBContext の Remove メソッドを使用して実行されますが、最初にデータベースにアクセスしてオブジェクトをロードし、次に再度削除する必要がないことに注意してください。通常、オブジェクトの ID が渡され、オブジェクトの新しいインスタンスをコンテキストにアタッチして削除できます。

public ActionResult DeleteInstructor(int instructorId)
        {
var instructor = new Instructor {Id = instructorId};
db.Instructors.Attach(instructor);
db.Instructors.Remove(instructor);
db.Instructors.SaveChanges();
            return View();
        }
于 2012-05-11T05:22:43.163 に答える
0

私はこれが古いスレッドであることを知っています。しかし、私はまったく同じことをしようとしていました

これが私の解決策です

//
    // GET: /Project/Create/

    public ActionResult Create()
    {
        var project = new Project();
        ViewBag.Themes = db.Theme.ToList();
        return View(project);
    }

    //
    // POST: /Project/Create/

    [HttpPost]
    public ActionResult Create(Project projet, string[] selectedTheme)
    {
        var errors = ModelState.Select(x => x.Value.Errors).ToList();
        project.Themes = new List<Theme>();

        if (TryUpdateModel(project, "", null, new string[] { "Theme" }))
        {
            try
            {
                UpdateProjectTheme(selectedTheme, project);

                db.Project.Add(project);
                db.SaveChanges();

                return RedirectToAction("Index");
            }
            catch (DataException)
            {
                //Log the error (add a variable name after DataException)
                ModelState.AddModelError("", "Impossible to create project.");
            }
        }
        return View(project);
    }

そして作成ビューで:

@{
  List<Project.Models.Theme> themes = ViewBag.Themes;
  @:<td>
    foreach (var display in themes)
  {

    <label class="checkbox">
        <input type="checkbox" 
                name="selectedTheme" 
                value="@display.ThemeID" /> 
        @display.Name
    </label>

    if (display.Name.Length > 20)
    {
        @:<br />
    }

    else
    {

        if (display.ThemeID % 2 == 0)
        {
            @:<br />
        }
    }
  }
   @:</td>
 @: </tr>
}

お役に立てば幸いです。私のSO投稿もご覧ください。

これは私の投稿です!!

于 2013-03-19T20:16:42.990 に答える