实体框架核心数据注释数据库生成的值 [英] Entity Framework Core Data Annotation Database Generated Values
问题描述
生成的属性似乎首先可以将数据注释用于生成的代码时间戳 属性,例如以 DateTime
类型创建/更新。
The Entity Framework Core documentation for Generated Properties makes it seem like Data Annotations can be used for generated code first "timestamp" properties such as created/updated on as a DateTime
type.
尝试在代码首次迁移时使用以下数据注释:
When trying to use the following data annotations along with code first migrations:
public class Foo {
// some properties
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime Created { get; set; }
// more properties
}
我收到了尝试执行命令 dotnet ef迁移时出现以下错误,在命令行中添加AddFooTimestamp
:
I receive the following error when attempting to execute command dotnet ef migrations add AddFooTimestamp
in the command line:
标识值生成不能用于
实体类型 Foo上的属性 Created,因为该属性类型为 DateTime。身份
值生成只能与带符号的整数属性一起使用。
Identity value generation cannot be used for the property 'Created' on entity type 'Foo' because the property type is 'DateTime'. Identity value generation can only be used with signed integer properties.
是否存在一种有效的方法来利用所描述的数据注释模型文档中的内容以及在EF Core和SQL Server环境中的代码优先迁移?或者只是 [Timestamp]
注释现在可以使用?
Is there an effective way to utilize the data annotations described in the documentation in the models along with code first migrations in a EF Core and SQL Server environment? OR is it just [Timestamp]
annotation that would be available at this time?
我的项目正在使用工具 Microsoft.EntityFrameworkCore.Tools
版本 1.0.0-preview2-final和 Microsoft.EntityFrameworkCore
& Microsoft.EntityFrameworkCore.SqlServer
版本 1.1.0。
My project is using tool Microsoft.EntityFrameworkCore.Tools
version "1.0.0-preview2-final" and Microsoft.EntityFrameworkCore
& Microsoft.EntityFrameworkCore.SqlServer
versions "1.1.0".
感谢您提供的任何帮助。
Thank you for any help you can provide.
推荐答案
必须在<$ c上设置 DateTime
模型属性$ c> INSERT 和 UPDATE
操作我结合了默认值通过 Fluent API
配置和数据库触发器。我在问题中提到的注释绝对不会自动将SQL Server配置为生成默认值或更新的 DateTime
值。
To have to DateTime
model properties that are set on INSERT
and UPDATE
actions I utilized a combination of Default Values via Fluent API
configuration and database triggers. The annotations I mentioned in my question absolutely do not automatically configure SQL Server to generated default or updated DateTime
values.
型号:
public class Foo {
// some properties
public DateTime Created { get; set; }
public DateTime LastUpdated { get; set; }
// more properties
}
默认值:
protected override void OnModelCreating(ModelBuilder modelBuilder)
modelBuilder.Entity<Foo>()
.Property(i => i.Created)
.HasDefaultValueSql("getdate()");
modelBuilder.Entity<Foo>()
.Property(i => i.LastUpdated)
.HasDefaultValueSql("getdate()");
}
数据库更新后触发:
CREATE TRIGGER [dbo].[Foo_UPDATE] ON [dbo].[Foo]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN;
DECLARE @Id INT
SELECT @Id = INSERTED.Id
FROM INSERTED
UPDATE dbo.Foo
SET LastUpdated = GETDATE()
WHERE Id = @Id
END
谢谢!
这篇关于实体框架核心数据注释数据库生成的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!