これらの2つのクラスがあるとします。新しいリポジトリを作成するのはいつどの時点で決定しますか?
public class Author
{
public int ID {get; set;}
public string Name{get; set;}
public virtual ICollection<Book> Books { get; set;}
}
public class Book
{
public int ID {get; set;}
public string Name{get; set;}
public int AuthorId {get; set;}
public virtual Author Author{ get; set;}
}
私はそのすべてのアクションが、私はこのアドレスに行くAuthorId
受けたBooksControllerお持ちの場合:
/著者/ 1 /書籍
はそれをしませんの現在のAuthorRepositoryを使用するだけですか?
public ActionResult Index(int AuthorId)
{
return View(_AuthorRepository.GetById(AuthorId).Books)
}
また、リポジトリ内のデータアクセスを維持するためにBookRepositoryを作成する必要がありますか?
public ActionResult Index(int AuthorId)
{
return View(_BookRepository.GetByAuthorId(AuthorId))
}
同じことが作成アクションで発生します。どちらが理にかなっているかを判断するのは苦労します。
[HttpPost]
public ActionResult Create(int AuthorId, BookViewModel book)
{
if(ModelState.IsValid)
{
Book b= new Book();
b= AutomapperMagicMethodThatGivesMeABookFromA(book); //
_AuthorRepository.FindById(AuthorId).Books.Add(b);
_AuthorRepository.SaveChanges();
return RedirectToAction("Index");
}
return View(book)
}
またはこの方法。
[HttpPost]
public ActionResult Create(int AuthorId, BookViewModel book)
{
if(ModelState.IsValid)
{
Book b= new Book();
b= AutomapperMagicMethodThatGivesMeABookFromA(book); //
b.AuthorId = AuthorId;
_BookRepository.Add(b);
_BookRepository.SaveChanges();
return RedirectToAction("Index");
}
return View(book)
}
このようなシナリオを処理するためのアドバイスをいただければ幸いです。 私のコードを自由に批評してください。
ありがとうございました。
ps。私はEFを使っています。
+1、非常に良い答え。 –
まあ、BooksControllerは、ユーザーが望むならば、ただ一つの本を編集/更新することもできなければなりません。 "/著者/ 1 /書籍/編集/ 5"のようなURLに行くことによって、Idによって本を見つけることは間違いなく要求されるでしょう.... BookRepositoryを作成するのに十分な理由はありますか? – ignaciofuentes