1

我是使用 Linq to Entities 的 Lambda 表达式的新手,希望在这里得到一些帮助。

我在主页上使用 ViewModel 来显示 2 列位置和公司下的文章列表。

article 类的简化视图如下所示:

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 表达式来根据我将提供的公司和位置列表返回文章。IE:

    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);
    }

在此先感谢您的帮助!

4

2 回答 2

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;
于 2013-04-05T03:38:42.230 回答
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]);
于 2013-03-29T07:37:27.080 回答