我不熟悉Lambq与Linq to Entities的经历,并希望在这里得到一些帮助。
我在我的主页上使用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; }
}
因此,我在文章和公司,文章和地点之间存在多对多的关系。我想在我的页面上显示的是与地点列表匹配的文章,以及与公司列表相匹配的文章。
我有一个ViewModel:
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);
}
提前感谢您的帮助!
答案 0 :(得分: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;
答案 1 :(得分: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]);