助けてくれてありがとう!以下の私の解決策は正しい答えに更新されました。
コントローラのリポジトリにアクセスする方法について簡単な質問があります。私のaddMovieメソッドを見ると、コントローラーがIMovieRepositoryを継承した後、ModelState.IsValid内でmovies.AddMovie(movie)を実行できると思いました。
IMovieRepository:
public interface IMovieRepository : IDisposable
{
IEnumerable<Movies> GetMovies();
Movies GetMovieByID(int id);
void AddMovie(Movies movie);
void UpdateMovie(Movies movie);
void DeleteMovie(int id);
void save(Movies movie);
}
MovieRepository:
public class MovieRepository : BaseRepository, IMovieRepository
{
private MovieContext db;
public MovieRepository(MovieContext repo)
{
db = repo;
}
public IEnumerable<Movies> GetMovies()
{
return db.Movies.ToList();
}
public Movies GetMovieByID(int id)
{
return db.Movies.Find(id);
}
public void AddMovie(Movies movie)
{
db.Movies.Add(movie);
}
public void UpdateMovie(Movies movie)
{
db.Entry(movie).State = EntityState.Modified;
}
public void DeleteMovie(int id)
{
Movies movie = db.Movies.Find(id);
db.Movies.Remove(movie);
}
public void save(Movies movie)
{
if (movie.movieID == 0)
db.Movies.Add(movie);
else
db.Entry<Movies>(movie).State = System.Data.EntityState.Modified;
db.SaveChanges();
}
}
NinjectDependencyResolve:
Bind<IMovieRepository>().To<MovieRepository>();
MoviesController:
public class MoviesController : Controller
{
private IMovieRepository movieRepository;
public MoviesController()
{
this.movieRepository = new MovieRepository(new MovieContext());
}
public MoviesController(IMovieRepository movieRepository)
{
this.movieRepository = movieRepository;
}
#region "GET"
//
// GET: /Admin/Movies/
public ActionResult Index()
{
return View();
}
#endregion
#region "POST"
[HttpPost]
public ActionResult addMovie(Movies movie)
{
if (ModelState.IsValid)
{
movieRepository.AddMovie(movie);
movieRepository.save(movie);
return RedirectToAction("index", "movies");
}
return View(movie);
}
#endregion
}
}