0

我的 LINQ to Entity 模型有很多问题。我是 C# 和 LINQ 的新手,所以请耐心等待。

我有一个包含图片和标签的模型,其中每张图片可以有很多标签,每个标签可以在很多图片上。在数据库中有一个正常的关系表,但在对象模型中,我将其视为 picture.tags (作为列表)和 tag.pictures (作为列表)。一个搜索查询包含多个标签,搜索的结果是包含所有带有我搜索过的所有标签(但可能更多)的图片。要搜索的标签数量不固定。

怎样才能最好地做到这一点?

4

3 回答 3

0

唔。'

我似乎无法让第二行工作,即 Contex.Pictures。上下文不允许。据我所知,这个算法会添加至少匹配一个标签的所有图片,而不仅仅是匹配所有标签的图片?还是我错了?

于 2009-07-11T13:30:58.320 回答
0

有很多方法可以做到这一点。这是一种方法。我不会声称它是“最好的”,但它会起作用。

IQueryable<Picture> FindByTags(IEnumerable<string> tags)
{
    var q = Context.Pictures;
    foreach (var tag in tags) 
    {
        q = q.Where(p => p.Tags.Any(t => t.Name == tag));
    }
    return q;
}
于 2009-07-10T17:11:51.637 回答
0
IQueryable<Picture> FindByTags(IEnumerable<string> included, IEnumerable<string> excluded)
{
      return (from p in context.Pictures
              where (from item in p.Tags
                     where included.Contains(item.Tag)
                     select 1).Count() == included.Count()
              where (from item in p.Tags
                     where excluded.Contains(item.Tag)
                     select 1).Count() == 0
              select p);
}

这也将允许排除,如果你不想要它,只需取出第二个。这也仅适用于图片没有重复标签的情况

于 2010-06-01T19:09:21.383 回答