【发布时间】:2019-04-11 11:36:46
【问题描述】:
使用标准脚手架仅在相关表的下拉列表中显示索引。如何显示多个字段,让下拉列表有意义?
我尝试使用 Shyju 在“使用实体框架从数据库表中获取数据”部分中概述的解决方案。 (Select Tag Helper in ASP.NET Core MVC)。
我在模型中有 2 个类(具有相关作者的书籍):
namespace SimpleAppwithTwoTables.Data
{
public class Book
{
public int BookID { get; set; }
[StringLength(255)]
[Display(Name ="Book Title")]
public string Title { get; set; }
public int AuthorID { get; set; }
public Author Author { get; set; }
}
}
和
namespace SimpleAppwithTwoTables.Data
{
public class Author
{
public int AuthorID { get; set; }
[Display(Name = "First Name")]
[StringLength(50)]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
[StringLength(50)]
public string LastName { get; set; }
public ICollection<Book> Books { get; set; } = new List<Book>();
}
}
BooksController 有一个 Create() 方法,类似于 Shyju 的帖子中描述的方法。
public IActionResult Create()
Author vm = new Author();
vm.Books = _context.Book.Select(a => new SelectListItem()
{ Value = a.AuthorID.ToString(), Text = a.Author.LastName }).ToList();
return View(vm);
}
控制器中的这一行
vm.Books = _context.Book.Select(a => new SelectListItem()
{ Value = a.AuthorID.ToString(), Text = a.Author.LastName }).ToList();
产生这个错误:
"不能隐式转换类型 'System.Collections.Generic.List
' 到 'System.Collections.Generic.ICollection '。 存在显式转换(您是否缺少演员表?)。
请注意,我是 C# 新手,并且了解这是一个类型转换问题,并且出现错误的行预期 Author 模型包含 ICollection。
我正在 vm.books 行中寻找不进行类型转换并与 ICollection 一起使用的代码。
【问题讨论】:
标签: c# asp.net-core asp.net-core-mvc entity-framework-core