[英]How to display data from related tables in View MVC4?
I have two tables: 我有两个表:
Category
=========
Id
Name
Entry
=======
Title
Name
Username
Password
CategoryId.
So I want the output to be All Entries listed but with Category.Name at the end. 所以我希望输出是列出的所有条目,但结尾是Category.Name。 EX.
EX。
ID Title Name Username Password Category
=== ===== ======== ========= ========= ===========
1 Facebook Peter Batman 123456 Social Network
So i have the Index method that returns list: 所以我有返回列表的Index方法:
public ActionResult Index()
{
IEnumerable<ListAllEntriesViewModel> query = null;
query = (from cat in _db.Categories
join en in _db.Entries on cat.Id equals en.CategoryId
select new
{
Id = cat.Id,
Title = en.Title,
Username = en.Username,
Password = en.Password,
Url = en.Url,
Description = en.Description,
CategoryName = cat.Name
}).AsEnumerable();
return View(query);
}
I have trouble converting it to IEnumerable. 我无法将其转换为IEnumerable。 Hhere is an error which cannot figure solution:
这是一个无法解决问题的错误:
Error 1 Cannot implicitly convert type
'System.Collections.Generic.IEnumerable<AnonymousType#1>' to
'System.Collections.Generic.IEnumerable<eManager.Web.Models.ListAllEntriesViewModel>'.
An explicit conversion exists (are you missing a cast?)
Any Help? 有帮助吗?
something like this you need to add ListAllEntriesViewModel
, because in your code the type is anonymous so make changes as shown in below code :- 像这样的事情,您需要添加
ListAllEntriesViewModel
,因为在您的代码中类型是匿名的,因此请按以下代码所示进行更改:
query = (from cat in _db.Categories
join en in _db.Entries on cat.Id equals en.CategoryId
select new ListAllEntriesViewModel
{
Id = cat.Id,
Title = en.Title,
Username = en.Username,
Password = en.Password,
Url = en.Url,
Description = en.Description,
CategoryName = cat.Name
}).AsEnumerable();
As the error says you are returning an IEnumerable of an anonymous type not of your Viewmodel. 如错误所示,您正在返回匿名类型的IEnumerable,而不是Viewmodel。 Assuming your viewmodel has all the required properties, you need to create a new
ListAllEntriesViewModel
in your select. 假设您的viewmodel具有所有必需的属性,则需要在您的选择中创建一个新的
ListAllEntriesViewModel
。
query = (from cat in _db.Categories
join en in _db.Entries on cat.Id equals en.CategoryId
select new ListAllEntriesViewModel()
{
Id = cat.Id,
Title = en.Title,
Username = en.Username,
Password = en.Password,
Url = en.Url,
Description = en.Description,
CategoryName = cat.Name
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.