多标签云相关帖子的实体框架查询

时间:2013-08-16 09:07:16

标签: c# .net entity-framework tags entity

如果我有像

这样的模型类
[Table("MTag")]
public class Tag
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int TagId { get; set; }
    public string TagLabel { get; set; }
    public virtual ICollection<TagRef> RefTags { get; set; }
}

[Table("TagRef")]
public class TagRef
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int TagRefId { get; set; }
    public virtual Tag Tag { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
}

[Table("Post")]
public class Post
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int PostId { get; set; }
    public UserProfile User { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string PostGuid { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
    public virtual ICollection<MTagRef> Tags { get; set; }
    public string ImageFileName { get; set; }
    public int Price { get; set; }
    public int ImageWidth { get; set; }
    public int ImageHeight { get; set; }

}

选择所有匹配的帖子有哪些可能的查询?如果我有汽车,移动设备如何设置查询等标签,你能否提示一下?

2 个答案:

答案 0 :(得分:0)

您有汽车,手机,车辆,电子产品等标签。

当你添加Post时,你会添加一些标签。当你添加一个问题时,你也可以添加一些标签,就像这个网站(Stackoverflow)一样。现在您要选择带有指定标签的所有帖子。

以下方法返回包含一些标记的所有帖子:

public static IQueryable<Post> PostsWithTags(List<int> tagIds)
{
        Context c = new Context();
        var Query = (from Group in c.TagRefs.GroupBy(g => g.TagId) let GroupTags = Group.Select(g => g.TagId) where tagIds.All(gt => GroupTags.Contains(gt)) select Group.Select(g => g.Post).FirstOrDefault());

        return Query ;
}

答案 1 :(得分:-1)

简单提示:

var tags = db.Post.Where(m=>m.YourPropertyName == "YourPropertyValue").ToList();

下面

YourPropertyName = with which property you want to match.

YourPropertyValue = Value of your property.