Search code examples
c#entity-frameworksqlitedefault

EF7 Error insert Default Date


I'm using EF7 with SQLite and define my class like this:

 class LogMessage
{
    public LogMessage()
    {

    }

    public DateTime? MessageDate { get; set; }
    public string Body { get; set; }

}

in the OnModelCreating I specify the default value like this:

modelBuilder.Entity<LogMessage>()
            .Property(m => m.MessageDate).HasDefaultValueSql("CURRENT_TIMESTAMP");

When I check the Database I got this structure that Looks fine to me:

CREATE TABLE "LogMessage" 
(
"MessageDate" TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP) CONSTRAINT "PK_LogMessage" PRIMARY KEY,
"Body" TEXT
)

But when I'm trying to add something to the entity with this code:

result = "a";
Message = new LogMessage();
Message.Body = result;
context.LogMessages.Add(Message);
context.SaveChanges();

I get this error:

An unhandled exception of type 'Microsoft.Data.Entity.DbUpdateConcurrencyException' occurred in EntityFramework.Core.dll Additional information: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded

Any idea about why I'm getting this error?


Solution

  • You can use Auto-Implemented Properties as shown below.

     class LogMessage
    {
        public LogMessage()
        {
    
        }
    
        public DateTime? MessageDate { get; set; } = DateTime.Now;
        public string Body { get; set; }
    
    }