How can I verify that my Linq IQueryable has performed

I am currently using Linq for NHibernate (although this is not a problem regarding this issue) to query my database, and I want to check if the current instance of IQueryable was running or not.

The debugger knows that my IQueryable was not called because it tells me that the extension of the Results property will "enumerate" it. Is there a way for me to also automatically identify this.

Hope this makes sense :)

+3
source share
3 answers

How about writing an IQueryable wrapper like this:

class QueryableWrapper<T> : IQueryable<T>
{
    private IQueryable<T> _InnerQueryable;
    private bool _HasExecuted;

    public QueryableWrapper(IQueryable<T> innerQueryable)
    {
        _InnerQueryable = innerQueryable;
    }

    public bool HasExecuted
    {
        get
        {
            return _HasExecuted;
        }
    }

    public IEnumerator<T> GetEnumerator()
    {
        _HasExecuted = true;

        return _InnerQueryable.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public Type ElementType
    {
        get { return _InnerQueryable.ElementType; }
    }

    public System.Linq.Expressions.Expression Expression
    {
        get { return _InnerQueryable.Expression; }
    }

    public IQueryProvider Provider
    {
        get { return _InnerQueryable.Provider; }
    }
}

Then you can use it as follows:

var query = new QueryableWrapper<string>(
    from str in myDataSource
    select str);

Debug.WriteLine("HasExecuted: " + query.HasExecuted.ToString());

foreach (string str in query)
{
    Debug.WriteLine(str);
}

Debug.WriteLine("HasExecuted: " + query.HasExecuted.ToString());

Output:

False
String0
String1
...
True

+1

, Visual Studio, DataContext.Log = Console.Out . SQL, , .

I am not sure if it is possible to programmatically check if the request has been completed. You can force it to execute, for example, by calling .ToListin a request.

0
source

Source: https://habr.com/ru/post/1696795/


All Articles