开发者

What's a LINQ query to search through related (1:m) records for a specific string?

开发者 https://www.devze.com 2023-04-11 03:44 出处:网络
I thought I\'d find an answer readily, but not so far. I have related tables -- Blog and Tags. The Tags schema looks like this:

I thought I'd find an answer readily, but not so far. I have related tables -- Blog and Tags. The Tags schema looks like this:

TagTableID (identity column)
BlogID (foreign key)
Tag (string)

The tables are related in SQL Server. Each blog entry can have multiple tags, and each tag for a blog entry generates a new entry 开发者_如何学Cin the Tags table. I want to search for blog entries that have specific tags in them. I can do this in Linq:

var blogQuery =
            from blogentry in blog.blogs
            where blogentry.Tags = [??]
            select blogentry;

Since there's multiple tags per blog entry, blogentry.Tags is available in Linq and returns an EntitySet. But I don't know how to search (I guess) the resulting collection to find a specific string. (The bit where it says [??] in the example above.)

I suspect this requires a more complex query, but this is where I've started ...


I assume you're using Linq 2 SQL or Linq 2 Entities?

I didn't test this, but I believe something like this should work:

var tagsToLookFor = new[] {"tag1", "tag2"}; 

var blogQuery = 
        from blogentry in blog.blogs 
        where blogentry.Tags.Any(t => tagsToLookFor.Contains(t.Tag))
        select blogentry; 

Do verify the resulting SQL with SQL profiler though.

0

精彩评论

暂无评论...
验证码 换一张
取 消