Lambda Expression for Many to Many realtionship in

2019-06-05 02:00发布

I'm using EF 5 Code First and VS 2012. I have classes for Articles and Tags. Each Article will have atleast one Tag associated. Please see the classes below.

public class Article
{
    public int ArticleId { get; set; }
    public virtual ICollection<ArticleTag> Tags { get; set; }
}
public class Tag
{
    public int TagId { get; set; }
    public string TagName { get; set; }
}

public class ArticleTag
{
    public int ArticleId { get; set; }
    public int TagId { get; set; }

    // navigation property
    public virtual Article Article { get; set; }
    public virtual Tag Tag { get; set; }
}

Below is the code I tried. requestTags contains the list of TadgIds. repBase is db context. But below code is returing all Articles.

var idList = requestTags.tags.Select(t => t.id).ToList();
 var result= repBase.GetAll<Article>().Select(tg => tg.Tags.Where(tk => idList.Contains(tk.TagId))).ToList();

Please hlep me to get list of articles for a given list of TagIds.

Thanks in advance.

1条回答
Animai°情兽
2楼-- · 2019-06-05 02:25

I think you are looking for this.

Change:

  • Select to Where
  • tg.Tags.Contains to tg.Tags.Any

example:

var idList = requestTags.tags.Select(t => t.id).ToList();

var result= repBase.GetAll<Article>().Where(tg => tg.Tags.Any(tk => idList.Contains(tk.TagId))).ToList();
查看更多
登录 后发表回答