Possible to default DateTime field to GETDATE() wi

2019-01-06 16:04发布

I added EntityFramework.Migrations (Beta 1) to an existing Code-First app that is going through some changes (for both migration capabilities and more fine-tuning of the tables I am generating from my code-first API) and ran into the GETDATE() scenario.

I was already using a custom initializer class in my DbContext to run SQL scripts to set some fields and create indexes in my database. A handful of my AlterTable scripts are primary just to setup fields with default values(such as certain DateTime fields being set to GETDATE()). I was really hoping EntityFramework.Migrations would have an answer for this since you can easily specify defaultValue, but so far I'm not seeing one.

Any ideas? I was really hoping that doing the following would magically work. (It is 'magic unicorn', after all)

DateCreated = c.DateTime(nullable: false, defaultValue: DateTime.Now)

Unfortunately, and logically, it set my default value to the time when the Update-Database command was executed.

7条回答
相关推荐>>
2楼-- · 2019-01-06 16:54

You must use custom SQL script in Up method for setting default value:

Sql("ALTER TABLE TableName ADD CONSTRAINT ConstraintName DEFAULT GETDATE() FOR ColumnName");

Setting default value in code allows only static values - no database level functions.

Anyway setting it in POCO constructor is correct way if you are going to use code first. Also if you want to set the value in the application for some special cases you cannot use a default value in the database because the default value in the database requires either DatabaseGeneratedOption.Identity or DatabaseGeneratedOption.Computed. Both these options allow setting the property only in the database.

Edit:

Since the product is still in development my answer is no longer valid. Check @gius answer for actual way to achieve this requirement by using defaultValueSql (it wasn't available in EF Migrations Beta 1 but was added in EF 4.3 Beta 1 which already includes migrations).

查看更多
登录 后发表回答