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

时间:2014-10-06 10:42:31

标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-4

我有两张桌子:

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

任何帮助?

2 个答案:

答案 0 :(得分:3)

这样你需要添加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();

答案 1 :(得分:1)

正如错误所示,您正在返回一个匿名类型的IEnumerable,而不是您的Viewmodel。假设您的viewmodel具有所有必需的属性,则需要在select中创建一个新的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
                 });