问题
According to the picture, I've designed 3 tables that are Article, Tag and ArticleTag. ArticleTag is a associated table between Article and Tag table. Now, I want to use Lambda expression to create a query that obtains articles according to TagId.
I've used Entity Framework 6.x First I got TagId according to tagTitle by a query.
// tagTitle is a parameter that passed to a method.
// isActiveTag is a parameter that passed to a method.
int currentTagId = DataContextFactory.GetDataContext()
.Tags.Where(p => p.Title == tagTitle && p.IsActive == isActiveTag)
.Select(p => p.Id).SingleOrDefault();
Now I want to use currentTagId for getting the Articles that related to it.
How can I create a query by Lambda expression that gets Articles according to the currentTagId?
public class Tag : Entity, ITag
{
public string Title { get; set; }
public string Description { get; set; }
public bool? IsActive { get; set; }
public virtual ISet<ArticleTag> ArticleTags { get; set; }
public virtual ISet<ProjectTag> ProjectTags { get; set; }
}
public class Article : Entity, IArticle
{
public virtual int? UserMemberShipId { get; set; }
public virtual string Title { get; set; }
public virtual string Summary { get; set; }
public virtual string Description { get; set; }
public virtual decimal? RateCounter { get; set; }
public virtual int? LikeCounter { get; set; }
public virtual bool IsActive { get; set; }
public virtual bool IsActiveNewComment { get; set; }
public virtual ISet<Comment> Comments { get; set; }
public virtual ISet<Rating> Ratings { get; set; }
public virtual ISet<AttachmentFile> AttachmentFiles { get; set; }
public virtual ISet<ArticleTag> ArticleTags { get; set; }
public virtual ISet<ArticleLike> ArticleLikes { get; set; }
}
public class ArticleTag : Entity, IArticleTag
{
public virtual int TagId { get; set; }
public virtual int ArticleId { get; set; }
public virtual Article Article { get; set; }
public virtual Tag Tag { get; set; }
public virtual int? Extra { get; set; }
}

回答1:
You're already filtering by the title you want, so you should be able to just join the other tables by their keys and select the matching "article" records.
Try this: (I can't test it of course, but see if it works)
var context = DataContextFactory.GetDataContext();
var articles = (from tag in context.Tags
join ta in context.ArticleTags on tag.Id equals ta.TagId
join article in context.Articles on ta.ArticleId equals article.Id
where tag.Title == tagTitle
&& tag.IsActive == isActiveTag
select article).ToList();
来源:https://stackoverflow.com/questions/25218665/using-lambda-expression-for-implementing-a-query-in-many-to-many-relation-tables