问题
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
}
I receive the following error when attempting to execute command dotnet ef migrations add AddFooTimestamp
in the command line:
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.
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?
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.
回答1:
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.
Model:
public class Foo {
// some properties
public DateTime Created { get; set; }
public DateTime LastUpdated { get; set; }
// more properties
}
Default Values:
protected override void OnModelCreating(ModelBuilder modelBuilder)
modelBuilder.Entity<Foo>()
.Property(i => i.Created)
.HasDefaultValueSql("getdate()");
modelBuilder.Entity<Foo>()
.Property(i => i.LastUpdated)
.HasDefaultValueSql("getdate()");
}
Database AFTER UPDATE Trigger:
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
Thanks!
来源:https://stackoverflow.com/questions/42036291/entity-framework-core-data-annotation-database-generated-values