使用Lambda表达式在多对多关系表中实现查询

时间:2014-08-09 12:38:53

标签: c# linq entity-framework lambda linq-to-entities

根据图片,我设计了3个表格,包括Article,Tag和ArticleTag。 ArticleTag是Article和Tag表之间的关联表。 现在,我想使用Lambda表达式创建一个根据TagId获取文章的查询。

我使用过Entity Framework 6.x. 首先,我通过查询根据tagTitle得到了TagId。

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

现在我想使用currentTagId来获取与之相关的文章。

如何根据currentTagId Lambda表达式创建查询?

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

enter image description here

1 个答案:

答案 0 :(得分:1)

您已经按照所需的标题进行过滤,因此您应该能够通过其键加入其他表并选择匹配的“文章”记录。

试试这个:(我当然不能测试它,但看看它是否有效)

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