2016-04-02 27 views
1

我有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屬性,這本書?

例如,在有趣的屬性我都17了,所以我希望檢索與標籤ID 17本書..

注:我的許多一對多的關係名稱生成表TagBooks

enter image description here

enter image description here

+0

爲什麼有趣的是不是一個int類型,雖然它收到一個tag_id? – CodeNotFound

+0

沒關係,假設它int –

回答

2

這應該給你在那裏與「雨燕」標籤相關的所有文章。

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

非常感謝你:) –

相關問題