Using 'Contains' Clause Like 'IN' SQL Clause in Entity Framework

asp.net c# contains entity-framework ienumerable

Question

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
1
8/20/2010 2:17:50 PM

Accepted Answer

Try the following:

var contents = db.Content.SelectMany(c => c.TagRelation).Where(tr => relations.Contains(tr)).ToList();
6
8/20/2010 2:22:26 PM

Popular Answer

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

}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow