2016-04-02 23 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

非常感谢你:) –

相关问题