繁体   English   中英

如何在View MVC4中显示相关表中的数据?

[英]How to display data from related tables in View MVC4?

我有两个表:

Category
=========
Id
Name 


Entry
=======
Title
Name
Username
Password
CategoryId. 

所以我希望输出是列出的所有条目,但结尾是Category.Name。 EX。

ID    Title     Name           Username     Password     Category
===   =====     ========       =========    =========    ===========
1     Facebook  Peter Batman   123456       Social        Network

所以我有返回列表的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);
    }

我无法将其转换为IEnumerable。 这是一个无法解决问题的错误:

 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?)

有帮助吗?

像这样的事情,您需要添加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();

如错误所示,您正在返回匿名类型的IEnumerable,而不是Viewmodel。 假设您的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM