WhyDidntItWork
asked on
Can't pass the proper value to the linq query variable.
Hi Experts,
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
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();
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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 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();
}
ASKER
Thanks for your help. Much appreciated.
Check query result for NULL and assign the value to avoid Error.
Open in new window