简体   繁体   English

在谓词表达式中传递where子句

[英]Passing a where clause in a predicate expression

I have the following predicate expression. 我有以下谓词表达。

public IQueryable<T> Find(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
    {
        return //boolean
    }

Here is where I am calling the method: 这是我调用该方法的地方:

    public void TestMethod1()
    {
        author.AuthorName = authorName;

        using (var context = new AspBlogRepository<Author>())
        {
            if (context.Find(e => e.AuthorName == authorName))
            {
                //do nothing
            }
            context.Add(author);   
        }
    }

I get an error saying that I you cannot convert an IQueryable to bool. 我收到一条错误消息,说我无法将IQueryable转换为bool。 I just want to be able to use my predicate expression to see if the author is already in the database. 我只希望能够使用我的谓词表达式来查看作者是否已经在数据库中。

Any help would be much appreciated. 任何帮助将非常感激。

Thanks! 谢谢!

Error says it all. 错误说明了一切。 context.Find(e => e.AuthorName == authorName) is returning IQueryable<T> . context.Find(e => e.AuthorName == authorName)返回IQueryable<T> If is expecting a bool If期待bool

So your usage of if (context.Find(e => e.AuthorName == authorName)) is wrong. 因此,您对if (context.Find(e => e.AuthorName == authorName))是错误的。 Change it to 更改为

if (context.Find(e => e.AuthorName == authorName).Any())
{

}

context.Find returns an IQueryable<T> . context.Find返回一个IQueryable<T> Your code could instead look like: 您的代码可能看起来像这样:

if (context.Find(e => e.AuthorName == authorName).Count() == 1)
{
    //do nothing
}
public IQueryable<T> Find(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
    {
        return //boolean
    }

The problem is here, if you indeed return boolean. 问题出在这里,如果您确实返回布尔值。 If this method is inside your context, you would first need to resolve Author and then filter the Authors in your repository. 如果此方法在您的上下文中,则首先需要解析Author ,然后在存储库中过滤Authors

If this is an EF context, and you have access to the EF context in your repository, you should be able to get the db set like this: 如果这是EF上下文,并且您可以访问存储库中的EF上下文,则应该能够像这样获取数据库集:

var entitySet = context.Set<T>();

Then, you can run your predicate against the entitySet returning the filtered results. 然后,您可以针对返回返回过滤结果的entitySet运行谓词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM