Entity Framework Core Data Annotation Database Generated Values

大兔子大兔子 提交于 2019-12-11 04:58:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!