我是MVC和LinqToSql的新手。我正在尝试创建一个使用这两种技术列出联系人的小应用程序。
我的型号:
public class Contact
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Range(18, 99)]
public int? Age { get; set; }
[EmailAddress]
public string Email { get; set; }
[Phone]
public string Phone { get; set; }
public Gender? Gender { get; set; }
public string Address { get; set; }
}
public enum Gender { Male, Female }
我的控制器:
public class ContactController : Controller
{
private string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
private LinqToSqlDataContext db;
public ActionResult Index()
{
using (db = new LinqToSqlDataContext(conStr))
{
var contacts = (IEnumerable)(from c in db.Contacts select c);
return View(contacts);
}
}
我的看法:
@model IEnumerable<ContactsApp.Models.Contact>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
...
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
...
</tr>
}
</table>
当我运行这个时,我收到以下错误:
传递到字典中的模型项的类型为'System.Data.Linq.DataQuery
1[ContactsApp.Contact]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
1 [ContactsApp.Models.Contact]'。
我理解View需要一个IEnumerable参数。我将查询转换为IEnumerable,但我仍然收到错误。
我很感激帮助理解我究竟做错了什么,以及解决这个问题的最有效方法是什么。
问题是您的查询返回IQueryable
(from c in db.Contacts select c) // <-- returns IQueryable
你需要将它转换为List(这是一个IEnumerable
)
using (db = new LinqToSqlDataContext(conStr))
{
var contacts = db.Contacts.ToList(); // <-- converts the result to List
return View(contacts);
}