简体   繁体   中英

EF CORE datetime saves with time 0

Good morning, I have imported my DB tables using DB-scaffold. In one table I have a datetime field where I need to add a DateTime.Now object but, when I save the changes to the DB the date saved is right but the time is 00:00:00.000.

Bellow an extract of my model

public partial class Vehicle
{
    // Some other properties....
    public DateTime LastImport { get; set; }
}

The DB Context

public partial class DBContext : DbContext
{
    // Some other properties....
    public virtual DbSet<Vehicle> Vehicles { get; set; }
    
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Some other model builders.
        modelBuilder.Entity<Vehicles>(entity =>
        {
            // Some other properties
            entity.Property(e => e.LastImport)
                .HasColumnType("datetime")
                .HasColumnName("last_import");

        });

        OnModelCreatingPartial(modelBuilder);
    }
}

And of the update method.

private static void UpdateVehicle(IEnumerable<ElencoVettureResponse> vehicles, DbContext ctx)
{
    foreach (var vehicle in vehicles)
    {
        var vehicleRecord = new Vehicle()
        {
            // Setting some other properties
            LastImport = DateTime.Now
        };

        ctx.Add(vehicleRecord);
    }

    ctx.SaveChanges();
}

The table CREATE script:

CREATE TABLE [dbo].[Vehicle](
/* SOME OTHER FIELDS */
[last_import] [datetime] NOT NULL

The field in my DB is filled like this:

数据库截图。

I want the fields to have a value something like this: " 2020-11-17 11:30:19.000 "

What do I have to do? Thank you.

var now = DateTime.Now;
var date = new DateTime(now.Year, now.Month, now.Day,
                        now.Hour, now.Minute, now.Second);

 LastImport = date;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM