Entity Framework Core Data Annotation Database Generated Values

c# data-annotations entity-framework-core sql-server

Question

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
1
2/5/2017 2:40:06 AM

Accepted Answer

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!

0
2/5/2017 3:45:59 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow