2009-11-18 52 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