2009-12-15 92 views
0

我试图从ASP.NET MVC应用程序中的一对多关系中检索数据。从一对多关系中检索数据

比方说,我有两个表的帖子和类别具有以下属性:

帖子 -id -title -category_id

类别 -id -name -author

我想抓取属于某个类别的帖子,并从类别中获取.name和.author的值。 这是我的模型:

public IQueryable<Post> GetPosts() 
{ 
    return from post in db.Posts 
      join categories in FindCategories() 
      on categories.id equals post.category_id 
      select new 
      { 
       title = post.title, 
       name = categories.name, 
       author = categories.author 
      }; 
    } 

和Controller:

public ActionResult Index() 
{ 
    var allposts = postRepository.GetPosts().ToList(); 
    return View(allposts); 
} 

模型的投诉,它不能转换和匿名的IQueryable的类型分为一个IQueryable <邮报>。我怀疑是因为我在做Select new {},但我不确定。
如果我只有IQueryable,那么我没有在视图中可用的ToList()方法。

所以,我迷路了。你能帮我吗? (顺便说一句,我是一个完整的新手在这个asp.net mvc的东西。)

+0

为什么该类别有作者?难道不是有作者的帖子吗? – 2009-12-15 07:12:57

+0

问题不在于MVC,而在于您的Linq代码。您正在创建一个匿名类型(选择new {title ...}),它不是您试图以IQueryable实体集返回的Post对象(IQueryable )。您需要定义另一个实体,比如说名为“PostForDisplay”的标题,名称和作者属性,并使用select PostForDisplay {title ... etc}并将返回类型设置为IQueryable 。我甚至不会进入你定义的结构的逻辑,但我同意上面的@AdamRalph。 – Lazarus 2009-12-15 07:31:03

+0

@Lazarus非常感谢。这帮助了我很多。出于某种原因,我相信我可以通过“即时”创建这些类来逃脱。 @AdamRalph是的,你是对的,它没有很大的意义,类别有一个作者。这个模型还有其他的一些东西,当我编辑问题的内容时,我犯了写错误的... – ojcar 2009-12-15 17:14:09

回答

1

这个问题已经在评论中由拉撒路回答。你的方法声明指出帖子的IQueryable的类型

public IQueryable<Post> GetPosts() { //... 

但是你的LINQ项目,一个匿名类型的返回类型,并返回一个IQueryable匿名类型

select new { //anonymous type 
    title = post.title, 
    name = categories.name, 
    author = categories.author 
}; // = IQueryable<SomeCompilerGeneratedTypeNameHere> 

的您需要定义一个新的类型

public class PostDisplay { 
    public string Title { get; set; } 
    public string Name { get; set; } 
    public string Author { get; set; } 
} 

然后在你的代码返回该类型的一个IQueryable

public IQueryable<PostDisplay> GetPosts() { 
    return from post in db.Posts 
     join categories in FindCategories() 
     on categories.id equals post.category_id 
     select new PostDisplay { 
        Title = post.title, 
        Name = categories.name, 
        Author = categories.author 
        }; 
} 
+0

谢谢DaveG。这解决了我的问题。 – ojcar 2009-12-15 17:15:43

2

我认为问题是你试图使用一个单一方法的范围以外的变种。在投影阶段,尝试新建Post对象而不是匿名类型。例如

public IQueryable<Post> GetPosts() 
{ 
return from post in db.Posts 
       join categories in FindCategories() 
       on categories.id equals post.category_id 
       select new Post() 
       { 
         title = post.title, 
         name = categories.name, 
         author = categories.author 
       }; 
} 
+0

如果我这样做,问题是模型Post不包含“name”的定义或“作者”... – ojcar 2009-12-15 08:08:37

+0

你的Post课程的定义是什么? – 2009-12-15 11:40:34