none
linq query will not accept null values RRS feed

  • Question

  • Why will this query not accept null values, it accepts mm/dd/yyyy but when I dont' entered anything it says datetime not valid. My database column is also set to allow null. You can try this query out yourself if you want because it works with Northwind.

    public partial class _Default : System.Web.UI.Page

    {

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

    //Create new instance

    DataClassesDataContext db = new DataClassesDataContext();

    //Search by ?

    var qry =

    from s in db.Employees

    where (

    s.BirthDate >= Convert.ToDateTime(txtFrom.Text) || (String.IsNullOrEmpty(txtFrom.Text))

    && s.BirthDate < Convert.ToDateTime(txtTo.Text) || (String.IsNullOrEmpty(txtTo.Text))

     

    )

    select new { s.EmployeeID, s.BirthDate };

    GridView1.DataSource = qry;

    GridView1.DataBind();

    }

    }

     

     

    <body>

    <form id="form1" runat="server">

    <div>

    BirthDate From

    <asp:TextBox ID="txtFrom" runat="server"></asp:TextBox>

    <br />

    BirthDate To

    <asp:TextBox ID="txtTo" runat="server"></asp:TextBox>

    </div>

    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Search" />

    <asp:GridView ID="GridView1" runat="server">

    </asp:GridView>

    </form>

    </body>

    Monday, December 8, 2008 1:36 AM

Answers

  • The null test should happen first so it doesn't attempt to convert if it is empty.

    You could also build this up programatically.

    [)amien
    Wednesday, April 15, 2009 6:12 AM
    Moderator

All replies

  • in VB I use the .hasvalue, i'm sure it's similar in c#



    for example

    Dim q = from u in db.users_
      where u.DateOfDeath.HasValue = False _
    select u


    this considers only the NULL values in that field


    (to do this, the property must be nullable = true in the datacontext designer)
    Monday, December 8, 2008 1:37 PM
  • The null test should happen first so it doesn't attempt to convert if it is empty.

    You could also build this up programatically.

    [)amien
    Wednesday, April 15, 2009 6:12 AM
    Moderator