简体   繁体   English

实体框架核心 2 HasDefaultValueSql() 不适用于 MySQL

[英]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.当我使用“NOW()”函数时,迁移有效,但正如我所说,数据库中未设置列默认值。 And when I try other MySql datetime functions I get this error:当我尝试其他 MySql datetime 函数时,我收到此错误:

You have an error in your SQL syntax;您的 SQL 语法有错误; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1检查与您的 MariaDB 服务器版本相对应的手册,以获取在第 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 .我遇到了完全相同的问题,当我按照本教程中的描述由.Net本身制作迁移文件时。

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.但是,这是一个错误,不是我的错,也不是 .Net 错误。

The problem actually came from a bug in Pomelo.EntityFrameworkCore.MySql library.问题实际上来自Pomelo.EntityFrameworkCore.MySql库中的一个错误。 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.无论如何,他们说他们也会很快为 MariaDB 解决这个问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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