【问题标题】:How can I search a database for tags relating to a post?如何在数据库中搜索与帖子相关的标签?
【发布时间】:2015-11-10 21:54:30
【问题描述】:

我有一个帖子和标签类

public class Post
{
    [Key]
    public int Id { get; set; }

    public string Title { get; set; }

    public DateTime DateTime { get; set; }

    public string Body { get; set; }

    public virtual ICollection<Tag> Tags
    {
        get
        {
            if (_tags == null)
            {
                _tags = new Collection<Tag>();
            }
            return _tags;
        }
        set { _tags = value; }
    }

    private ICollection<Tag> _tags;
}

public class Tag
{
    [Key]
    public int Id { get; set; }

    [Required]
    [MaxLength(50)]
    [Index(IsUnique = true)]
    public string Name { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
}

我正在尝试按标签搜索帖子。

这是我的搜索方法

    public ActionResult Search(int id)
    {

        var posts = from p in db.Posts
                    from t in db.Tags
                    where p.Tags.Contains(t)
                    select p;
        foreach (var post in posts)
        {
            Console.WriteLine(string.Format("Post Name {0}", post.Title));
        }

    }

但这绝对行不通,因为 p.Tags 是一个集合。

那么我如何返回一个包含标签的帖子列表,该标签带有给函数的 id?

【问题讨论】:

    标签: c# asp.net-mvc database linq


    【解决方案1】:
    var posts = db.Posts.Where(p=>p.Tags.Any(t=>t.id==id));
    

    【讨论】:

    • 谢谢你,传奇。我正在寻找应该是 Any 的 contains。
    • 作为记录,这应该也可以,但它不是那么干净或清晰:var posts = db.Posts.Where(p=&gt;p.Tags.Select(t=&gt;t.id).Contains(id));
    猜你喜欢
    • 1970-01-01
    • 2014-06-26
    • 2019-11-09
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 2016-05-16
    • 2013-01-10
    相关资源
    最近更新 更多