在实体框架中使用'包含'子句类似'IN'SQL子句

时间:2010-08-20 14:17:50

标签: c# asp.net entity-framework ienumerable contains

我正在开发一个标签云应用程序。有3个数据库表。

内容:ContentID,文字

标记:TagID,名称

TagRelation :TagRelationID,TagID,ContentID

以下代码错误。因为'Contains'子句不采用像'IN'SQL子句这样的参数列表。是否有可用于使此代码有效的替代子句?

        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 个答案:

答案 0 :(得分:6)

尝试以下方法:

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

答案 1 :(得分:0)

可能this Stackoverflow thread可以帮助你,至少我认为你正在寻找这个......

摘自主题:

你可以实现自己的WhereIn方法:

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

用法:

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

您的示例(未经测试) :(并进行2次查询:()

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

}