Ошибка MVC - требуется элемент модели типа IEnumerable - PullRequest
0 голосов
/ 19 апреля 2019

Я новичок в 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);
        }
    }

My View:

@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].

Я понимаю, что представление ожидает параметр IEnumerable. Я привел запрос к IEnumerable, но все еще получаю сообщение об ошибке.

Буду признателен за помощь в понимании того, что именно я делаю неправильно, и как наиболее эффективно решить эту проблему.

1 Ответ

0 голосов
/ 20 апреля 2019

Проблема в том, что ваш запрос возвращает IQueryable

(from c in db.Contacts select c) // <-- returns IQueryable

Вам необходимо преобразовать его в список (который является IEnumerable)

using (db = new LinqToSqlDataContext(conStr))
{
    var contacts = db.Contacts.ToList(); // <-- converts the result to List
    return View(contacts);
}
...