views:

50

answers:

2

I am working on a tag cloud application. There are 3 database tables.

Content: ContentID, Text

Tag: TagID, Name

TagRelation: TagRelationID, TagID, ContentID

The code below is wrong. Because 'Contains' clause doesn't take a list of parameters like the 'IN' SQL clause. Is there an alternative clause that I can use to make this code work?

        public List<Content> GetTagArticles(String tagName)
    {
        var relations = db.TagRelation.Where(t => t.Tag.Name == tagName).ToList();

        var contents = db.Content.Where(c => c.TagRelation.Contains(relations)).ToList();



        return contents.ToList();

    }
+1  A: 

Try the following:

var contents = db.Content.SelectMany(c => c.TagRelation).Where(tr => relations.Contains(tr)).ToList();
Ben Robinson
Your suggestion works. Thanks.
gavss
But why does it return related TagRelations?
gavss
Sorry are you asking why this works?
Ben Robinson
A: 

Hi,

Probably this Stackoverflow thread can help you, at least I think you are looking for this...

Excerpt from the thread:

you could implement your own WhereIn method :

public static IQueryable<TEntity> WhereIn<TEntity, TValue>
 (
     this ObjectQuery<TEntity> query, 
     Expression<Func<TEntity, TValue>> selector, 
     IEnumerable<TValue> collection
 )
{
    if (selector == null) throw new ArgumentNullException("selector");
    if (collection == null) throw new ArgumentNullException("collection");
    ParameterExpression p = selector.Parameters.Single();

    if (!collection.Any()) return query;

    IEnumerable<Expression> equals = collection.Select(value => 
      (Expression)Expression.Equal(selector.Body, 
       Expression.Constant(value, typeof(TValue))));

    Expression body = equals.Aggregate((accumulate, equal) => 
    Expression.Or(accumulate, equal));

    return query.Where(Expression.Lambda<Func<TEntity, bool>>(body, p));
}

Usage:

public static void Main(string[] args)
{
    using (Context context = new Context())
    {
        //args contains arg.Arg
        var arguments = context.Arguments.WhereIn(arg => arg.Arg, args);   
    }
}

Your example (untested): (and doing 2 queries :( )

public List<Content> GetTagArticles(String tagName)
{
    var relationIds = db.TagRelation.Where(t => t.Tag.Name == tagName).Select(t=>t.Id).ToList();

    var contents = db.Content.WhereIn(c => c.TagRelation.Id, relationIds>);



    return contents.ToList();

}
Stephane