如何检索与特定标签相关的书籍

时间:2016-04-02 17:54:24

标签: asp.net asp.net-mvc asp.net-mvc-4

我有3张桌子(User, Tags, Book)。

User表中,我有一个属性Interesting,它有一个tag_id(我在其中保存了一个tagid)。我还有一个Tags表,其中有许多标签,其中包含多对多的书签关系。

public class Tag
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual string UrlSlug { get; set; }
    public virtual string Description { get; set; }

    public virtual ICollection<Book> Books { get; set; }
}

这是书表:

public partial class Book
{
    [Key]
    public int Book_id { get; set; }

    [Required]
    [Display(Name ="User Name")]
    [StringLength(128)]
    public string User_ID { get; set; }

    public virtual ICollection<Tag> Tags { get; set; }
    public virtual AspNetUser AspNetUser { get; set; }
}

这是用户表:

public partial class AspNetUser
{      
    public string Id { get; set; }
    public string Email { get; set; }
    public bool EmailConfirmed { get; set; }
    public string PasswordHash { get; set; }

    [Display(Name = "Interesting")]
    public int Interesting { get; set; }

    public virtual ICollection<Book> Books { get; set; }
}

这里的SQL语句是什么来检索与Interesting属性匹配的书?

例如,在Interesting属性中我有17个,所以我想检索与标签id 17相关的书。

注意:从关系名称生成的多对多表是TagBooks

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

这应该会为您提供与“Swift”标签相关联的所有帖子。

var books = dbContext.Books.Where(s => s.Tags.Any(f => f.Name == "Swift")).ToList();

如果您想根据TagId获得结果,请更改谓词中的条件。

var books = dbContext.Books.Where(s => s.Tags.Any(f => f.Id== 17)).ToList();
相关问题