Neel
Neel

Reputation: 1951

How do i check if my Linq query produced any result?

Hi guys I am using entity framework, I am facing some problem while checking if my linq returned any results, if it returns any result I want to use it as a data source, the following is the code please have a look:

    var dbContext = new DBEntities();
    try
    {
        var linQuery = from cq in dbContext.tblCharacteristics
                        where cq.CharacteristicID.Equals(combobox1.SelectedText)
                        select new
                        {
                            CharacteristicIDs = cq.CharID,
                            CharacteristicNames = cq.CharName
                        };

        if (linQuery.Any()) //Also tried with linQuery.Count() != 0
        {
            lbChaKeyValues.DataSource = linQuery;
            lbChaKeyValues.DisplayMember = "CharacteristicNames";
        }
    }
    catch (System.Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        dbContext.Dispose();
    }

I am getting following error : "DbComparisonExpression requires arguments with comparable types."

Upvotes: 1

Views: 3232

Answers (1)

Paul Alexander
Paul Alexander

Reputation: 32367

IF CharacteristicID is an integer type, the comparison won't work. Instead try

   var inputFromUser = Int32.Parse( combobox1.SelectedText );

   var linQuery = from cq in dbContext.tblCharacteristics
                    where cq.CharacteristicID == inputFromUser
                    select new
                    {
                        CharacteristicIDs = cq.CharID,
                        CharacteristicNames = cq.CharName
                    };

Incidentally .Any() is the correct way to test for search results. And if you're not going to use the return results, there's no need to project the data into an anonymous type. Just use select true or select cq which allows the optimizer to use the best index in the DB.

Upvotes: 3

Related Questions