问题描述
我有两张表,Tags(tagid, postid, tagname) 和 posts(postid, name, ...)
现在我想做一个查询,返回所有具有通用标签数量的帖子.比如:我想要所有带有标签 asp.net 和 jquery 的帖子
正如我所说,要查找的标签数量是通用的
我该怎么做?
谢谢
2009 年 11 月 17 日更新:有一个问题:表之间的关系不存在,因为我的主键在 2 个字段上(用于版本控制)我怎样才能使它没有关系?我正在使用 Linq To 实体
此外,查询应该具有良好的性能,并且不应发出数千个服务器请求.
我猜你不能在我遇到问题的 EF 3.5 中使用 .Contains().我通过使用这个WhereIn"扩展解决了这个问题
'Contains()' 使用 Linq to Entities 解决方法?p>
把它放到一个静态类中,然后你可以使用类似的东西:
IQueryablePostsWithByTags(IEnumerable<string> tagNames){var postIds = context.Tags.Select(t=>t.postid);foreach(tagNames 中的 var 标记){postIds = context.Tags.WhereIn(t=> t.postid, postIds).Where(t=>t.tagname == tag);}返回 context.Tags.Where(t=> t.posId, postIds)}
我真的认为你应该看看你的表之间的关系.
I have two tables, Tags(tagid, postid, tagname) and posts(postid, name, ...)
now i want to make a query that returns me all posts that have a generic amount of tags.
like: i want all posts that have the tag asp.net AND jquery
as i said, the amount of tags to look for is generic
how can i do something like that?
thx
update 17.11.2009: there is one problem: the relation betwenn the tables does not exist, because my primary key is on 2 fields (for versioning) how can i make it without a relation? Im using Linq To Entities
also, the query should have good performance, and should not make thousands of server requests.
I guess you can't use .Contains() using EF 3.5 which I have had a problem with. I got around this by using this "WhereIn" extension
'Contains()' workaround using Linq to Entities?
put this into a static class then you could use something like:
IQueryable<Post> PostsWithByTags(IEnumerable<string> tagNames)
{
var postIds = context.Tags.Select(t=>t.postid);
foreach (var tag in tagNames)
{
postIds = context.Tags
.WhereIn(t=> t.postid, postIds)
.Where(t=>t.tagname == tag);
}
return context.Tags.Where( t=> t.posId, postIds)
}
I really think you should look at having relationships between your tables though.
这篇关于标签系统的 linq 查询 - 搜索多个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!