I’m having a trouble filtering/ joining in-memory object lists with Linq to objects, and for what would normally be a trivial SQL query…
Scenario:
Have a json service(.asmx) allows client to make a DB call through Entity Framework wrapped sproc (function import). In this case a [Web Method] “GetArticles(int [] TagIds)”
I’m now looking to cache this data to save on DB calls and apply filters to the cached collection.
Data:
- Many to many relationship with 2 Entities: Articles, Tags
- Articles can have many tags, and tags can be associated with many articles, ( so extra link table ‘ArticlesTags’)
The web service filter param will contain an array of TagId’s that returned articles can have.
So my baseline SQL query would look like so
SELECT DISTINCT a.*
FROM Article a INNER JOIN ArticlesTags at ON a.ArticleId = at.ArticleId
WHERE at.TagId in (0, 1.. 'list of tag ids')
I’m hitting a number of snags –
EF wrapped sprocs don’t allow SQL 2008 (Table Value Parameters) so i can’t pass in TagId list filter in the preferred format.
I have found an example where two result sets can be returned from one sproc call which may get around that.
So once I have the two collections (Articles and ArticlesTags) which I intend to cache, how does one join and subsequently filter based on the possible TagId’s filter param with linq-to-objects?
Here is one way to “rewrite” your SQL query in LINQ:
This prints: