I have an Entity Framework model based on an existing database (also called "Code First from database"). The database contains a
movies table with the following columns:
id int IDENTITY(1,1) NOT NULL
name nvarchar(50) NOT NULL
releaseDate date NOT NULL
releaseDate column has SQL data type
date, so it does not contain time portion. Entity Framework maps this data type to CLR
DateTime type that does contain time portion.
Now I am going to add a new
movie to the database. Important part here is that my new
movie has some time portion specified in its
var movie = new movie
name = "Hello World",
releaseDate = DateTime.Now // releaseDate contains time portion
using (var context = new Model())
Console.WriteLine(movie.id); // id field was updated automatically
Console.WriteLine(movie.releaseDate); // releaseDate was not updated and still contains time portion
Now my new
movie is stored in the database, and, obviously, time portion of
releaseDate was ignored — only date part was stored in the DB. However, if I look at the
movie.releaseDate, the time portion is still there.
I am wondering, how consistent is that behavior? Why does not Entity Framework update
releaseDate to set its time portion to
00:00:00? Since it automatically populated the
movie.id property with auto-generated primary key value, why doesn't it do similar thing for
Is there any way to enforce Entity Framework to truncate time portion of
DateTime value mapped to SQL
EF only updates the auto generated primary key. It doesn't load the whole entity back.
If you run a SQl Server trace you'll see that it performs an INSERT followed by a SELECT of only the primary key. In the example below I have a table Orders.
exec sp_executesql N'INSERT [Purchasing].[Orders]([ClientCode], [OrderDate]) VALUES (@0, @1) SELECT [OrderId] FROM [Purchasing].[Orders] WHERE @@ROWCOUNT > 0 AND [OrderId] = scope_identity()',N'@0 nvarchar(max) ,@1 datetime2(7)',@0=N'X',@1='2015-11-30 15:11:36.4326217'