Lambda Expression for Many to Many realtionship in C# EF 5 Code First

自古美人都是妖i 提交于 2019-12-08 06:33:29

问题


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:


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


来源:https://stackoverflow.com/questions/13051330/lambda-expression-for-many-to-many-realtionship-in-c-sharp-ef-5-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!