2013-03-29 62 views
1

我是新來的Lambda期待與Linq實體,並希望在這裏得到一些幫助。實體框架在ViewModel和多對多關係中的Lambda表達式

我在我的主頁上使用ViewModel來顯示2列,位置和公司下的文章列表。

文章類的簡化圖如下所示:

public class Article 
{ 
    [Key] 
    public int ArticleID { get; set; } 

    public string Title { get; set; } 

    public virtual ICollection<Location> Locations { get; set; } 
    public virtual ICollection<Company> Companies { get; set; } 

} 

和位置是這樣的:

public class Location 
{ 
    [Key] 
    public int LocationID { get; set; } 

    public string LocationName { get; set; } 

    public virtual ICollection<Article> Articles { get; set; } 
} 

最後,一個公司看起來是這樣的:

public class Company 
{ 
    [Key] 
    public int CompanyID { get; set; } 

    public string CompanyName { get; set; } 

    public virtual ICollection<Article> Articles { get; set; } 
} 

所以我有一個多對多的文章和公司之間的關係,文章和地點。我想在我的網頁上展示的是與地點列表匹配的文章,以及與公司列表相匹配的文章。

我有一個視圖模型:

public class HomePageViewModel 
{ 
    public IEnumerable<Article> CompanyArticles { get; set; } 
    public IEnumerable<Article> LocationArticles { get; set; } 

} 

而且我與Lambda表達式返回基於公司和地點,我會提供的名單上的文章中掙扎。即:

public ActionResult Index() 
    { 

     var Companies = new List<Company> 
     { 
      new Company {CompanyName ="foo"}, 
      new Company {CompanyName ="bar"} 
     }; 

     var Locations= new List<Location> 
     { 
      new Location {LocationName ="UK"}, 
      new Location {LocationName ="US"} 
     }; 
     var viewModel = new HomePageViewModel(); 

     viewModel.CompanyArticles = // what do I put here? 
     viewModel.LocationArticles = // what do I put here? 

     return View(viewModel); 
    } 

在此先感謝您的幫助!

回答

1

這應該是什麼你後:

 viewModel.CompanyArticles = from a in db.Articles 
            where 
            (
            from c in a.Companies 
            where InterestingCompanies.Contains(c.Name) 
            select c 
            ).Any() 
            select a; 


     viewModel.LocationArticles = from a in db.Articles 
            where 
            (
            from l in a.Locations 
            where InterestingLocations.Contains(l.Name) 
            select l 
            ).Any() 
            select a; 
+0

完美!到底是什麼我以後。 –

0

我真的覺得你不需要你的ViewModel。因爲您在多對多關係中沒有附加信息。

var articles = new List<Article> 
{ 
    new Article {Title = "any1", Locations = new List<Location>(), 
       Companies = new List<Company>()}, 
    new Article {Title = "any2", Locations = new List<Location>(), 
       Companies = new List<Company>()} 

}; 

articles[0].Companies.Add(Companies[0]); 
articles[0].Locations.Add(Locations[0]); 
+0

感謝,但我認爲我需要一個視圖模型,因爲我在我的視圖中顯示多個模型?此外,我試圖解決的問題是LINQ查詢獲取所有文章的位置和公司名單 - 我看不出你的答案會告訴我... –