Link to home
Start Free TrialLog in
Avatar of WhyDidntItWork
WhyDidntItWork

asked on

Can't pass the proper value to the linq query variable.

Hi Experts,

ABCEntities Context = new ABCEntities();

                int val = int.Parse(workOrderDropDownList.SelectedValue.ToString());

                var woDateQuery = (from p in Context.WOes
                                  where p.WorkOrder == val
                                  select p.Date);
                                
                dateRequestedLabel.Text = woDateQuery.ToString();

Open in new window


When I run this query, instead of getting a date as anticipated, I get what appears to be a version of the query:

The dateRequestedLabel reads: "SELECT [Extent1].[Date] AS [Date] FROM [dbo].[WO] AS [Extent1] WHERE [Extent1].[WorkOrder] = @p__linq__0"

Thanks in advance for your help.

W
ASKER CERTIFIED SOLUTION
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi,

Check query result for NULL and assign the value to avoid Error.

var woDateQuery = (from p in Context.WOes
                                  where p.WorkOrder == val
                                  select p.Date);

if(woDateQuery.FirstOrDefault() != null)
{
      dateRequestedLabel.Text = woDateQuery.FirstOrDefault().Date.ToString();
}

Open in new window

Hi WhyDidntItWork;

The query that you posted has not yet executed and the reason why you are seeing the query that will be sent to the SQL server, once you cause the query to be enumerated over that query will return a collection of objects and NOT a single instance of an object. If you are expecting a single object to be return then you need to pull that object out of the collection and assign it to a variable. The code snippet below should do what you need.

// The query retuning a single object of date or null
var woDateQuery = (from p in Context.WOes
                   where p.WorkOrder == val
                   select p.Date).FirstOrDefault();

// Set up a variable that will a string version of a DateTime object
string woDateStr = "Returned an empty Collection";
// Test to see if a value was returned and if so fill the woDateStr variable
if( woDateQuery != null )
{
    woDateStr = woDateQuery.ToString();
}

Open in new window

Avatar of WhyDidntItWork
WhyDidntItWork

ASKER

Thanks for your help.  Much appreciated.