Это мой репозиторий:
namespace Repositories
{
public class AuthorRepository : IAuthorRepository
{
AppContext myDB = new AppContext();
public List<Author> GetAllFromRepo()
{
return myDB.Authors.ToList();
}
}
}
Мой сервисный файл:
namespace Services
{
public class AuthorService : IAuthorService
{
private readonly IAuthorRepository _AuthorRepository;
public AuthorService(IAuthorRepository authorRepository)
{
_AuthorRepository = authorRepository;
}
public List<AuthorViewModel> GetAll()
{
List<Author> authors = _AuthorRepository.GetAllFromRepo();
return authors.Select( x => new AuthorViewModel()
{
ID = x.ID,
FullName = $"{x.FirstName } {x.LastName} ",
Books = x.Books.Select(g => new BookViewModel()
{
ID = g.ID,
Name = g.Name
}).ToList()
}).ToList();
}
}
}
Мой автор Просмотр модели:
namespace ViewModels
{
public class AuthorViewModel
{
public AuthorViewModel()
{
Books = new List<BookViewModel>();
}
public int ID { get; set; }
public string FullName { get; set; }
public List<BookViewModel> Books { get; set; }
}
}
Книги Смотреть модель:
namespace ViewModels
{
public class BookViewModel
{
public int ID { get; set; }
public string Name { get; set; }
public AuthorViewModel Author { get; set; }
}
}
Контроллеры:
public class HomeController : Controller
{
private readonly IAuthorService _AuthorService;
// GET: Home
public HomeController(IAuthorService authorService)
{
_AuthorService = authorService;
}
public ActionResult Index()
{
List<AuthorViewModel> Authors = _AuthorService.GetAll();
ViewBag.myAuthors = Authors;
return View();
}
[HttpGet]
public ActionResult Books(int id)
{
List<AuthorViewModel> Authors = _AuthorService.GetAll();
ViewBag.Books = from a in Authors
where a.ID == id
select a.Books;
return View();
}
}
Контроллер индекса работает нормально. Но когда я вызываю контроллер Books, он выдает мне эту ошибку в моем браузере:
'System.Collections.Generic.List' не содержит определения для 'ID'
Ошибка источника:
Line 18: {
Line 19: <tr>
Line 20: <td>@book.ID</td> // this is the error line
Line 21: <td>@book.Name</td>
Line 22: <td><a href="~/Home/Index">Home</a></td>
Исходный файл: C: \ Users \ Jack \ Desktop \ WebApp ver 1.2 \ WebApp \ Views \ Home \ Books.cshtml Строка: 20
Модель просмотра для книг:
@{
ViewBag.Title = "Books";
}
<h2>Books</h2>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Action</th>
</tr>
@foreach (var book in ViewBag.Books)
{
<tr>
<td>@book.ID</td>
<td>@book.ID</td>
<td><a href="~/Home/Index">Home</a></td>
</tr>
}
</table>
Здесь, в модели представления индекса, все работает нормально:
@{
ViewBag.Title = "Index";
}
<h2>Author List</h2>
<table>
<tr>
<th>ID</th>
<th>FullName</th>
<th>Details</th>
<th>Books</th>
</tr>
@foreach (var author in ViewBag.myAuthors)
{
<tr>
<td>@author.ID</td>
<td>@author.FullName</td>
<td><a href="~/Home/Meh/@author.ID">Details</a></td>
<td><a href="~/Home/Books/@author.ID">Books</a></td>
</tr>
}
</table>
Буду признателен за любые указания и помощь, почему я не могу перечислить книги в представлении.