locked
How to check if SELECT returns data (safe check) RRS feed

  • Question

  • User-1186424966 posted

    Hello

    I have a lot o SELECT statements in my web. I always uses something like this to check if there is data available.

    var data = db.Query(selectQuery, ID);
    
    if (data.Count() > 0) ...

    Now I have SELECT with JOIN and see the error:

    Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Nevyvolatelného člena System.Collections.ObjectModel.ReadOnlyCollection<object>.Count nelze použít jako metodu. (--can't be used as method)

    I've found Mike's info about using data.Any(). Unfortunatelly it generates another error.

    Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: System.Collections.ObjectModel.ReadOnlyCollection<object> neobsahuje definici pro Any. (--there is no definition for Any)

    So I tried (data != null) and it works. Also works (data.Count > 0).

    My question is - what's the one and only safe way how to check SELECT returns data regardless what's inside the SEELCT?

     

    Vladimir

    Tuesday, June 11, 2013 6:13 AM

Answers

  • User-821857111 posted

    If Count() and Any() did not work, it was most likely a result of passing in a dynamic type as a parameter value somewhere. In turn, that changes the return type of the Query() method to simply "dynamic". 

    For example, you might have a query that produces a single value:

    var categoryId = db.QueryValue(@"SELECT CategoryId FROM Categories WHERE CategoryName  = 'Beverages'");

    categoryId is a dynamic type. If you pass that into a Query method call, the return type becomes dynamic:

    var data = db.Query(@"SELECT * FROM Products WHERE CategoryId = @0", categoryId);

    If you use Visual Studio and hover over var in the line above, you will see simply "dynamic". Any and Count are extension methods on Enumerable, but dynamic does not support extension methods - hence the error message you see. So you can specify the return type explicitly:

    IEnumerable<dynamic> data = db.Query(@"SELECT * FROM Products WHERE CategoryId = @0", categoryId);

    or cast the dynamic:

    var data = db.Query(@"SELECT * FROM Products WHERE CategoryId = @0", (int)categoryId);

    Then the return type will support Any() and Count() and all other extensions methods.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 11, 2013 6:42 AM