0

I am using Entity Framework 6 and SQL Server 2014 to store data. I have a table with 4 column, and the CreatedOn column has a default with current datetime in SQL Server.

When I add record in table from SQL Server by writing query it works correctly, but when I try to add record from Entity Framework, it fills in null into the CreatedOn column.

My table schema is:

enter image description here

My ASP.NET code-behind looks like this:

enter image description here

I also try by changing column datatype to datetime2, but no luck.

What changes do I need to make to make it work with EF? I don't want to pass date from asp.net.

When I see output of select getutcdate() in SQL Server, it shows the correct value.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Keval Patel
  • 925
  • 4
  • 24
  • 46
  • The problem is that your `Contact` class has a property `DateTime createdOn` and because you dont explicitly set it, it has a default value (of `DateTime.MinValue`) which EF will save. –  Oct 17 '15 at 06:00
  • I have changed datetime to datetime2 in sql and set it default as getutcdate(), I updated my question, please check and give any suggestion – Keval Patel Oct 17 '15 at 06:07
  • Why it's storing null and not getutcdate() ? – Keval Patel Oct 17 '15 at 06:08
  • Because now (based on your edit), your passing `null` so EF sets the vale as `null`. AFAIK, there is no way other than to set the the value explicitly. –  Oct 17 '15 at 06:10
  • But it's not a good idea to set date in business logic, because it would created a problem in future when I put my application on multiple servers, all will give their own date and time. So for this reason, I set date in sql server itself – Keval Patel Oct 17 '15 at 06:12
  • 1
    But you can use `DateTime.UtcNow` –  Oct 17 '15 at 06:15
  • 1
    The [answers here](http://stackoverflow.com/questions/5965386/is-there-an-easy-way-to-make-entityframework-use-sql-default-values) might help. –  Oct 17 '15 at 06:26
  • I am using DateTime.UtcNow in asp.net and passing to sql to entities. Hope it will not create trouble in future :) – Keval Patel Oct 17 '15 at 07:04

0 Answers0