我正在尝试创建一个没有Entity框架的MVC项目,我收到了这个错误。没有为此对象定义的无参数构造函数。我是C#的新手,我想要一些帮助。这是我的代码: 首先是模型Movies.cs
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 :(得分:2)
如果没有注册依赖注入框架,则无法在控制器的构造函数中指定参数。
要么改变这个:
public MovieController(IMovieRepository repository)
{
this.repository = repository;
}
到
public MovieController()
{
this.repository = new MovieDBRepository();
}
或设置依赖注入引擎,如Unity,Ninject或fFastInjector。