Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting record in SQL table with timestamp datatype

I have a SQL Table with TimeStamp Column. The corresponding EF entity is below

 public partial class Request : IEntityBase
{
    public Request()
    {            
    }

    public int RequestID { get; set; }
    public Nullable<int> BatchID { get; set; }
    public string ClientID { get; set; }
    public Nullable<System.DateTime> CreatedDateTime { get; set; }
    public Nullable<System.DateTime> ModifiedDateTime { get; set; }
    public byte[] VersionStamp { get; set; }        
}

The VersionStamp property has datatype timestamp is sql

In C# i create a new entity and call savechanges()

        var request = new Request()
        {
            ClientID = "XYZ",
            CreatedDateTime = DateTime.Now,
            ModifiedDateTime = DateTime.Now,
        };            
        await _DBContext.SaveChangesAsync().ConfigureAwait(false);

But i get error

"Cannot insert an explicit value into a timestamp column. Use INSERT with a column list to exclude the timestamp column, or insert a DEFAULT into the timestamp column."

I am not setting timestamp anywhere in the code. I was expecting SQL will automatically update the column value

like image 915
LP13 Avatar asked Aug 22 '17 19:08

LP13


People also ask

How do I insert date and timestamp in SQL?

Insert the date with the TO_DATE function. SQL> INSERT INTO table_dt VALUES(4, TO_DATE('01-JAN-2003', 'DD-MON-YYYY')); Display the data. Set the timestamp format.

How do I write a timestamp in SQL query?

MySQL TIMESTAMP() Function The TIMESTAMP() function returns a datetime value based on a date or datetime value. Note: If there are specified two arguments with this function, it first adds the second argument to the first, and then returns a datetime value.


1 Answers

For EF Core 2.0 (and propably EF Core 1.0 as well) you have to specify timestamp/version property inside DbContext/OnModelCreating mehod.

Below you can find sample specification for the "Request" type.

modelBuilder.Entity<Request>(entity =>
{
     entity.ToTable("Requests");           // Depends on your table name 
     entity.HasKey(e => e.RequestID)       // If you have a primary key
           .HasName("PK_Requests");

     entity.Property(e => e.VersionStamp)
           .IsConcurrencyToken()           // If you want to handle concurrency
           .ValueGeneratedOnAddOrUpdate(); // This is important
});
like image 105
Tomino Avatar answered Oct 27 '22 15:10

Tomino