title: How to avoid empty date getting converted to DateTime.Min value when saving to database? Entity Frameworks
body: <p>I have a form with text box for date input. If I Provide date everything is fine. If I don't provide date (I leave it empty), DateTime.min (1/1/0001) value is sent. And this causes error: <strong>The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value</strong></p>
  
  <p>My date property is defined as nullable:</p>
  
  <pre><code>public Nullable&lt;System.DateTime&gt; InstallDate { get; set; }
  </code></pre>
  
  <p>What I want is null value to be written to database if I don't provide date.
  I know I could in my update method check for 1/1/0001 and send null, but, do I have to do that? <strong>Is there a way around this problem?</strong> Thanks </p>
  
  <p><strong>EDIT:</strong></p>
  
  <p><strong>I solved the problem adding code below into my update method:</strong></p>
  
  <pre><code>tank.InstallDate = tank.InstallDate == DateTime.MinValue ? null : tank.InstallDate;
  </code></pre>
  
  <p>So my code looks like this:</p>
  
  <pre><code>public void UpdateTank(Tank tank)
  {
      using (RetailFuelEntities ctx = new RetailFuelEntities())
      {
          tank.InstallDate = tank.InstallDate == DateTime.MinValue ? null : tank.InstallDate;
          ctx.Tanks.Attach(tank);
          ctx.Entry(tank).State = EntityState.Modified;
          ctx.SaveChanges();
      }
  }
  </code></pre>
  
  <p>Here is my ObjectDataSource:</p>
  
  <pre><code>&lt;asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetTank"
                              TypeName="DataAccess.Fuel.EF4.Tanks" DataObjectTypeName="DataAccess.Fuel.EF4.Tank"
                              DeleteMethod="DeleteTank" InsertMethod="InsertTank" UpdateMethod="UpdateTank"&gt;
                              &lt;SelectParameters&gt;
                                  &lt;asp:ControlParameter ControlID="TextBoxTankId" Name="TankId" PropertyName="Text"
                                      Type="String" /&gt;
                              &lt;/SelectParameters&gt;
                          &lt;/asp:ObjectDataSource&gt;
  </code></pre>
  
  <p>I wonder if null checking can be avoided.</p>