我正在尝试在MVC中使用以下代码,这是我迄今为止所做的:
public class MoviesModel
{
public int Id { get; set; }
public string MovieName { get; set; }
public string Actor { get; set; }
public int Year { get; set; }
}
控制器
public MoviesModel Index()
{
MoviesModel myModel;
string connectionString =
"";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand com = con.CreateCommand();
com.CommandText = "SELECT [ID] ,[MovieName] ,[Actor] ,[Year] FROM [dbo].[Movies]";
con.Open();
using (SqlDataReader reader = com.ExecuteReader())
{
while (reader.Read())
{
myModel = new MoviesModel
{
myModel.Id = Convert.ToInt32(reader[0]),
myModel.MovieName = reader[1].ToString(),
myModel.Actor = reader[2].ToString(),
myModel.Year = Convert.ToInt32(reader[3])
};
}
}
con.Close();
return myModel;
}
但我收到的错误
cannot initialize class with a collection because it does not implement System.Collection.IEnumerable
答案 0 :(得分:1)
实际上,我把它拿回来了。我认为这可能是编译错误的根源(告诉我们编译器抱怨的行会有所帮助)。您获得的编译错误带有文件名和行号,我保证这些内容不会指向您引用的任何代码。
myModel = new MoviesModel
{
myModel.Id = Convert.ToInt32(reader[0]),
myModel.MovieName = reader[1].ToString(),
myModel.Actor = reader[2].ToString(),
myModel.Year = Convert.ToInt32(reader[3])
};
这不是正确的语法。大括号内部是为了初始化myModel
而运行的代码 - 你不能在括号内引用myModel
,因为它在括号中的代码之后才存在完成执行。幸运的是,您不需要,因为这是设置这些属性的语法:
myModel = new MoviesModel
{
Id = Convert.ToInt32(reader[0]),
MovieName = reader[1].ToString(),
Actor = reader[2].ToString(),
Year = Convert.ToInt32(reader[3])
};
更广泛地说,我会想到你真正想要做的是返回一组MoviesModel对象,而不是一个恰好是结果集中最后一部影片的MoviesModel对象。执行此操作的代码如下所示:
public ActionResult Index()
{
var models = new List<MoviesModel>();
string connectionString = "";
using (var con = new SqlConnection(connectionString))
using (var com = con.CreateCommand())
{
com.CommandText = "SELECT [ID] ,[MovieName] ,[Actor] ,[Year] FROM [dbo].[Movies]";
con.Open();
using (var reader = com.ExecuteReader())
{
while (reader.Read())
{
var myModel = new MoviesModel
{
Id = reader.GetInt32(0),
MovieName = reader.GetString(1),
Actor = reader.GetString(2),
Year = reader.GetInt32(3)
};
models.Add(myModel);
}
}
}
return View(models);
}
顺便说一句,Convert.ToInt32
是一种非常低效的方法,可以在数据库和读者中获得已经是整数的东西。 GetInt32
方法效果会更好。