none
linq to sql nullable object RRS feed

  • Question

  • 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 complete_date.

    Here is the code I am referring to:

    try
    {
    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);
                }
    }

    When there is nothing returned from the linq query and the code is on the statement,
    (complete_date != 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?


    Thursday, October 11, 2012 3:33 AM

Answers

  • The ? means the DateTime datatype will be "nullable", meaning your query may or may not return a null.
    Friday, October 12, 2012 5:25 PM

All replies

  • Hi wendy elizabeth,

    Welcome to MSDN Forum.

    I'm not clear about the issue? Could you please clarify what leads to the exception? Based on the code, even the linq query returns nothing, the if statement will judge if the object is null, it will not step to the catch block. Furthermore, I think you need to define the complete_date as nullable.

    Best Regards


    Allen Li [MSFT]
    MSDN Community Support | Feedback to us


    Friday, October 12, 2012 3:40 AM
    Moderator
  • Can you tell me what  you mean by ", I think you need to define the complete_date as nullable."? Are you referring to how the complete-date is defined in the database or some declaration that is used  in linq? Can you show me some code so I can see what you are referring to?
    Friday, October 12, 2012 4:16 AM
  • Hi wendy elizabeth,

    Sorry for unclear reply. The return value from the linq may null, so please define your complete_date as:

    DateTime? complete_date = (DateTime)(from a in rData.eStag where a.PID == pId select a.Complete_Date).FirstOrDefault();

    Best Regards

    Allen Li [MSFT]
    MSDN Community Support | Feedback to us

    Friday, October 12, 2012 4:21 AM
    Moderator
  • You can define a variable as "DateTime? complete_date". What does the question mark after the datetime mean?
    Friday, October 12, 2012 2:32 PM
  • The ? means the DateTime datatype will be "nullable", meaning your query may or may not return a null.
    Friday, October 12, 2012 5:25 PM