0

MvcMusicStoreの例でEntity Frameworkの代わりにFluent NHibernateを使用しようとしていますが、Createを使用してArtistIdとGenreIdに入力して問題が発生しています表示します。以下のように見えるコントローラにメソッドを作成します
MVCでFluent NHibernateを使用してCreateビューのオブジェクトをマップする

public class AlbumMap:ClassMap<Album> 
    { 
     public AlbumMap() 
     { 
      Id(x => x.AlbumId); 
      Map(x => x.AlbumArtUrl); 
      References(x => x.Artist).Cascade.All().Column("ArtistId"); 
      References(x => x.Genre).Cascade.All().Column("GenreId"); 
      Map(x => x.Price); 
      Map(x => x.Title); 
     } 
    } 

:私は私のアルバム地図で

私は他のオブジェクトを参照しています、事実とは何かだと思う

public ActionResult Create() 
    { 
     MusicRepository repository = new MusicRepository(); 
     ViewBag.ArtistId = new SelectList(repository.GetArtists(), "ArtistId", "Name"); 
     ViewBag.GenreId = new SelectList(repository.GetGenres(), "GenreId", "Name"); 
     return View(); 
    } 

と問題が発生しているCreateビューの部分は次のとおりです。

<div class="editor-label"> 
     @Html.LabelFor(model => model.Genre, "Genre") 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownList("GenreId", String.Empty) 
     @Html.ValidationMessageFor(model => model.Genre) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Artist, "Artist") 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownList("ArtistId", String.Empty) 
     @Html.ValidationMessageFor(model => model.Artist) 
    </div> 

データベースでは、新しいアルバムを作成した後、TitleやAlbumUrlなどの他のフィールドは入力されますが、ArtistIdとGenreIdはnullに設定されます。

答えて

0

あなたはおそらく私がこれについて全く新しいと言うことはできますが、私は実際に私の問題を解決しました。私は戻って保存することを可能にするためにdropdownlistforし、最初のDropDownListヘルパーを変更することによって、これをしなかった:

<div class="editor-label"> 
     @Html.LabelFor(model => model.Genre, "Genre") 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownListFor(model => model.Genre.GenreId, (SelectList)ViewBag.GenreId,"Please select") 
     @Html.ValidationMessageFor(model => model.Genre.GenreId) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Artist, "Artist") 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownListFor(model => model.Artist.ArtistId, (SelectList)ViewBag.ArtistId,"Please select") 
     @Html.ValidationMessageFor(model => model.Artist.ArtistId) 
    </div> 

は、これは私の初期化アーティストやジャンルの特性を持つアルバムを返されました。唯一のことはIdプロパティしか含んでいなかったので、保存する前に残りのプロパティ(nhibernateを使用)を取得するためにこれらを使用しなければならないということでした:

[HttpPost] 
    public ActionResult Create(Album album) 
    { 
     try 
     { 
      MusicRepository repository = new MusicRepository(); 
      if (ModelState.IsValid) 
      { 
       album.Artist = repository.GetArtistById(album.Artist.ArtistId); 
       album.Genre = repository.GetGenreById(album.Genre.GenreId); 
       repository.AddAlbum(album); 
       return RedirectToAction("Index"); 
      } 
      ViewBag.ArtistId = new SelectList(repository.GetArtists(), "ArtistId", "Name"); 
      ViewBag.GenreId = new SelectList(repository.GetGenres(), "GenreId", "Name"); 
      return View(album); 
     } 
関連する問題