2015-02-09 90 views
-1

我想創建一個沒有實體框架的MVC項目,並且出現此錯誤。沒有爲此對象定義的無參數構造函數。我在C#中很新,我想要一些幫助。這裏是我的代碼: 首先,模型Movies.cs沒有爲此對象定義的無參數構造函數 - MVC項目

using System; 
using System.Collections.Generic; 
using System.Data.SqlClient; 
using System.Linq; 
using System.Web; 

namespace MyMovies.Models 
{ 
    public class Movie 
    { 
     public int ID { get; set; } 
     public string Title { get; set; } 
     public DateTime ReleaseDate { get; set; } 
     public string Genre { get; set; } 
     public decimal Price { get; set; } 
     public string Rating { get; set; } 
    } 

    public interface IMovieRepository 
    { 
     IEnumerable<Movie> Get(); 

    } 

    public class MovieDBRepository : IMovieRepository 
    { 
     public IEnumerable<Movie> Get() 
     { 
      string connectionString = "Connection"; 
      using (var conn = new SqlConnection(connectionString)) 
      using (var cmd = conn.CreateCommand()) 
      { 
       conn.Open(); 
       cmd.CommandText = "SELECT ID, Title, Date, Genre, Rating"; 
       using (var reader = cmd.ExecuteReader()) 
       { 
        while (reader.Read()) 
        { 
         yield return new Movie 
         { 
          ID = reader.GetInt32(reader.GetOrdinal("ID")), 
          Title = reader.GetString(reader.GetOrdinal("name")), 
          ReleaseDate = reader.GetDateTime(reader.GetOrdinal("ReleaseDate")), 
          Genre = reader.GetString(reader.GetOrdinal("Genre")), 
          //Price = reader.GetFloat(reader.GetOrdinal.("Price")), 
          Rating = reader.GetString(reader.GetOrdinal("Rating")) 
         }; 
        } 
       } 
      } 
     } 
    } 
} 

,這是控制器

using MyMovies.Models; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace MyMovies.Controllers 
{ 
    public class MovieController : Controller 
    { 



     private readonly IMovieRepository repository; 
      public MovieController(IMovieRepository repository) 
      { 
       this.repository = repository; 
      } 
      // GET: Movie 
      public ActionResult Index() 
      { 
       var movie = this.repository.Get(); 
       return View(movie); 
      } 


      } 
    } 
+0

Movie類的定義是什麼? – 2015-02-09 15:18:54

+0

使用像Ninject這樣的DI容器來配置它(或者你可以編寫你自己的'IDependencyResolver')。 – Styxxy 2015-02-09 15:20:37

+0

我該怎麼做?我很抱歉,但我沒有編程經驗。 – Celia 2015-02-09 15:23:36

回答

2

,如果你沒有一個依賴注入不能在指定的構造函數控制器的參數框架註冊。

要麼改變此:

 public MovieController(IMovieRepository repository) 
     { 
      this.repository = repository; 
     } 

 public MovieController() 
     { 
      this.repository = new MovieDBRepository(); 
     } 

或建立一個依賴注入引擎,如統一,Ninject,或fFastInjector。

+0

非常感謝你......它的工作原理! – Celia 2015-02-09 15:38:46

相關問題