2009-11-18 48 views
1

联接表我的应用程序的结构为:ASP.NET MVC - 使用LINQ

namespace DomainModel.Abstract 
{ 
    public interface IContentItemsRepository 
    { 
     IQueryable<Content> ContentItems { get; } 
     IQueryable<Category> Categories { get; } 
     IQueryable<ContentCategory> ContentCategories { get; } 
    } 
} 

namespace DomainModel.Entities 
{ 
    [Table(Name = "Content")] 
    public class Content 
    { 
     [Column(IsPrimaryKey = true, 
       IsDbGenerated = true, 
       AutoSync = AutoSync.OnInsert)] 
     public int content_id { get; set; } 
     [Column] 
     public string type { get; set; } // article, video, recipe, tool 
     [Column] 
     public string title { get; set; } 
... 

namespace DomainModel.Entities 
{ 
    [Table(Name = "Content_Categories")] 
    public class ContentCategory 
    { 
     [Column(IsPrimaryKey = true, 
       IsDbGenerated = true, 
       AutoSync = AutoSync.OnInsert)] 
     public int content_category_id { get; set; } 
     [Column] 
     public int content_id { get; set; } 
     [Column] 
     public int category_id { get; set; } 
... 

namespace DomainModel.Entities 
{ 
    [Table(Name = "Categories")] 
    public class Category 
    { 
     [Column(IsPrimaryKey = true, 
       IsDbGenerated = true, 
       AutoSync = AutoSync.OnInsert)] 
     public int category_id { get; set; } 
     [Column] 
     public string category_name { get; set; } 
     [Column] 
     public string type { get; set; } //recipe,tool,other 
     [Column] 
     public int ordering { get; set; } 
... 

我可以这样做:

var articlesInCategory = _contentRepository.ContentItems 
      .Where(x => x.type == "article"); 

,并得到的文章列表。没问题。

但是,我现在需要根据类别选择内容。所以,我需要将Content to ContentCategory加入到Category中。

我不知道如何做到这一点。任何帮助都感激不尽。

谢谢。

编辑:

我想我的问题的一部分是,我甚至不知道该怎么称呼我在做什么,所以很难寻找这一点。我甚至在做LINQ to SQL,或LINQ to Entities,还是LINQ to Objects?

+0

不是真正的mvc问题。你也应该添加一个linq-to-sql标签。 – 2009-11-18 22:55:16

回答

1

连接查询将是这样的。

var content= 
from category in _contentRepository.Category 
join contentCategory in _contentRepository.ContentCategory 
on category.category_id equals contentCategory.category_id 
join content in _contentRepository.Content 
on content.content_id equals contentCategory.content_id 
where [email protected] 
select new {type , title } 
+0

我在第二个“加入”和“其中”出现错误:预期的上下文关键字'等于' – Scott 2009-11-18 23:25:18

+0

抱歉,编辑我的查询,连接应该在外键上使用相等。 – 2009-11-19 03:16:11

1

您正在寻找的概念在linq中被称为SelectMany,并且有许多方法可以实现它。

之一是:

var content = 
from category in _categoryRepository.CategoryItems 
join contCat in _contentCategoryRepository.Items 
on category.category_id == conCat.category_id 
where category.category_id == parameter 
select contCat.content_id; 

从这里,你应该能够把它扩大到拉出所有你需要的数据...看看到into关键字,并检查了this link,如果你还没有准备好。

+0

当你连接两个表时,你需要指定一些连接列吗? – 2009-11-18 23:15:31

+0

哎呦:)感谢您的支持。 – 2009-11-18 23:54:04