简体   繁体   中英

Entity Framework Core 2 HasDefaultValueSql() not working with MySQL

So, I have a Model with a prop like this:

public DateTime Date { get; set; }

Im trying to set a default value to this field like this:

modelBuilder.Entity<Record>().Property(r => r.Date).HasDefaultValueSql("NOW()");

The problem is that the database column default value isnt set. When I use the "NOW()" function, the migration works but as I said, the column default isnt set in the database. And when I try other MySql datetime functions I get this error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1

What am I missing here?

I had exactly same problem, while I made the migration files by .Net itself as described in this tutorial .

entity.Property(e => e.ValidFrom)
                    .HasColumnName("valid_from")
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("'current_timestamp()'"); //<-- Line of problem!

I didn't expected for any error in an auto generated code! However, it was a bug not my fault or .Net bug.

The problem actually came from a bug in Pomelo.EntityFrameworkCore.MySql library. I discussed it with the developers here .

As I he said:

So you have to remove the single quotes ...

I removed the single quotes and the problem resolved .

At the end the solution was:

entity.Property(e => e.ValidFrom)
                    .HasColumnName("valid_from")
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("current_timestamp()"); 

Anyway, they said they will solve it for MariaDB also very soon.

我认为你必须使用“getdate()”而不是“NOW()”

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