[英]No parameterless constructor defined for this object - MVC project
I am trying to create a MVC project without Entity framework and I get this error. 我试图创建没有实体框架的MVC项目,但出现此错误。 No parameterless constructor defined for this object.
没有为此对象定义无参数构造函数。 I am pretty new in C# and I would like some help.
我在C#中还很陌生,希望获得一些帮助。 Here is my code: First the model Movies.cs
这是我的代码:首先是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"))
};
}
}
}
}
}
}
and this is the controller 这是控制器
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);
}
}
}
You cannot specify a parameter in the constructor for a controller if you do not have a dependency injection framework registered. 如果没有注册依赖项注入框架,则不能在控制器的构造函数中指定参数。
Either change this: 更改此:
public MovieController(IMovieRepository repository)
{
this.repository = repository;
}
to 至
public MovieController()
{
this.repository = new MovieDBRepository();
}
or set up a dependency injection engine such as Unity, Ninject, or fFastInjector. 或设置依赖项注入引擎,例如Unity,Ninject或fFastInjector。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.