【发布时间】:2011-07-29 05:09:00
【问题描述】:
假设你有这两个类。
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;}
}
如果我有一个 BooksController,它的所有操作都会收到一个 AuthorId
我去这个地址:
/Authors/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,如果有什么不同的话。
【问题讨论】:
标签: asp.net-mvc entity-framework repository repository-pattern