C# Entity Framework 6 Code First 插入时的默认日期时间值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17048125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:28:03  来源:igfitidea点击:

Entity Framework 6 Code First default datetime value on insert

c#.netsqlentity-framework

提问by Atrotygma

When I'm saving changes to the database, I'm running into the following exception:

当我保存对数据库的更改时,我遇到了以下异常:

Cannot insert the value NULL into column 'Registered', table
'EIT.Enterprise.KMS.dbo.LicenseEntry'; column does not allow nulls.
INSERT fails. The statement has been terminated.

The related code first model property looks like this:

相关代码第一个模型属性如下所示:

[DatabaseGenerated(DatabaseGeneratedOption.Identity), DataMember]
public DateTime         Registered          { get; private set; }

... and here's why I'm confused: As far as I know, by providing the annotation [DatabaseGenerated(DatabaseGeneratedOption.Identity)I'm ordering Entity Framework to auto-generate the field (in this case: Only once at creation time.)

...这就是我感到困惑的原因:据我所知,通过提供注释,[DatabaseGenerated(DatabaseGeneratedOption.Identity)我命令 Entity Framework 自动生成该字段(在这种情况下:仅在创建时一次。)

So I'm expecting to have a non-nullable (required) field, without the possibility to alter the field manually where EF is taking care of.

所以我希望有一个不可为空的(必填)字段,而无法手动更改 EF 处理的字段。

What am I doing wrong?

我究竟做错了什么?



Notes:

笔记:

  1. I don't want to use Fluent-API, as I want to use POCOs.
  2. The property defaultValueSqlis also not an option, because I need to rely database independed for this project (e.g. for GETDATE()).
  3. I'm using Entity Framework 6 alpha 3, Code First.
  1. 我不想使用 Fluent-API,因为我想使用 POCO。
  2. 该属性defaultValueSql也不是一个选项,因为我需要依赖独立于该项目的数据库(例如 for GETDATE())。
  3. 我正在使用实体框架 6 alpha 3,代码优先。

采纳答案by Sparky

Try this:

尝试这个:

[DatabaseGenerated(DatabaseGeneratedOption.Identity), DataMember]
public DateTime?            Registered          { get; private set; }

The question mark makes the property nullable

问号使属性可以为空

回答by marcellscarlett

There is no default DateTime. Only a min value.

没有默认的日期时间。只有一个最小值

You could potentially just set the datetime on that entity before calling dbContext.SaveChanges.

您可能只是在调用之前在该实体上设置日期时间 dbContext.SaveChanges

See this for a solution.

请参阅此解决方案。

回答by Jeremy Cook

This technique behaves like a readonlyfield that is persisted to the database. Once the value is set it cannot (easily) be changed by using code. (Of course, you change the setter to publicor internalif needed.)

这种技术的行为就像一个readonly持久化到数据库的字段。一旦设置了值,就不能(很容易)使用代码更改它。(当然,如果需要,您可以将 setter 更改为publicinternal。)

When you create a new instance of a class that uses this code Registeredwill not initially be set. The first time the value of Registeredis requested it will see that it has not been assigned one and then default to DateTime.Now. You can change this to DateTime.UTCNowif needed.

当您创建使用此代码的类的新实例时,Registered最初不会设置。第一次Registered请求的值时,它会看到它尚未分配一个,然后默认为DateTime.NowDateTime.UTCNow如果需要,您可以将其更改为。

When fetching one or more entities from the database, Entity Framework will set the value of Registered, including privatesetters like this.

当从数据库中获取一个或多个实体时,实体框架将设置 的值Registered,包括private像这样的设置器。

private DateTime? registered;
[Required]
public DateTime Registered
{
    get
    {
        if (registered == null)
        {
            registered = DateTime.Now;
        }
        return registered.Value;
    }
    private set { registered = value; }
}

回答by Martin Kunc

What I did was I set value as optional and nullable. I used Data Annotation, but its also possible to use IsOptional in Fluent Api:

我所做的是将值设置为可选和可为空。我使用了数据注释,但也可以在 Fluent Api 中使用 IsOptional:

        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public DateTime? UpdatedAt { get; set; }

Then I created another Sql migration, to alter value to default:

然后我创建了另一个 Sql 迁移,将值更改为默认值:

    public partial class AlterTableUpdatedAtDefault : DbMigration
    {
        public override void Up()
        {
            Sql(@"ALTER TABLE dbo.[Table]
                  ADD CONSTRAINT DF_Table_UpdatedAt
                  DEFAULT getdate() FOR UpdatedAt");
        }

        public override void Down()
        {
            Sql(@"ALTER TABLE dbo.[Table]
                  drop CONSTRAINT DF_Table_UpdatedAt");
        }
    }