1

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();

    }

2 Answers 2

6

Try the following:

var contents = db.Content.SelectMany(c => c.TagRelation).Where(tr => relations.Contains(tr)).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

But why does it return related TagRelations?
0

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();

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.