In a C# 2008 application, I am using linq to sql to connect to a sql server 2008 r2 database. One of the linq statements returns the value to a datetime field called startdate.
My first if test looks like
if (startdate != null).
When there is nothing returned from the linq query and the code is on the statement,
(startdate != null), the program then lands on the catch statement of a try catch block.
Thus can you tell me what I can do so the the application does not land on the catch block code with an exception. I would think there is a way to obtain the datetime value when nothing is returned.
Can you show me what code solves the problem and explain how it solves the problem?
Loading
VulpesPosted Oct 12, 2012, 4:33 AM
If there are no records returned by the query, then complete_date will be equal to default(DateTime) - it can't be null because it's not a nullable DateTime.
It therefore follows that if isn't null and it isn't default(DateTime), then it must be some other DateTime value - namely the value of the a.Complete_Date column for the first (or only) record returned.
You should use the debugger to track down errors by seeing what the values of variables actually are when the program runs (just hover your mouse over them). If you're not sure how to use the debugger, then the insertion of a MessageBox.Show, Console.WriteLine or Debug.WriteLine can be just as informative.
dcPosted Oct 12, 2012, 12:09 AM
Could the following statement be causing my error:
if (complete_date != null && complete_date != default(DateTime))
If so, can you tell me why it could be causing the error?
VulpesPosted Oct 11, 2012, 1:58 PM
Also the clause: complete_date != null is unnecessary as complete_date is a non-nullable DateTime and so can't be null.
That reduces your code to the following:
// code
If you're still getting an exception thrown, then it's probably something you're doing inside the 'if' statement - it can't be the 'if' statement itself and the LINQ query looks OK to me.
dcPosted Oct 11, 2012, 11:14 AM
{
DateTime complete_date = (DateTime)(from a in rData.eStag
where a.PID == pId
select a.Complete_Date).FirstOrDefault();
if (complete_date != null && complete_date != default(DateTime))
{
}
catch
{
catch (Exception e)
{
throw new Exception(e.Message);
}
}
Can you tell me what you think is wrong with it when no records are selected from the database?
VulpesPosted Oct 11, 2012, 5:19 AM