Entity Framework Database Annotation Master Data

The Core Entity Framework documentation for Generated Properties makes it appear that data annotations can be used for generated code first "timestamp" , for example, created / updated as a type DateTime

.

When trying to use the following data annotations along with the first code migrations:

public class Foo {
    // some properties

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public DateTime Created { get; set; }

    // more properties
}

      

When trying to run a command dotnet ef migrations add AddFooTimestamp

on the command line, the following error appears:

Identity value creation cannot be used for the 'Created' on entity type 'Foo' property because the property type is 'DateTime'. identity value generation can only be used with signed integer values.

Is there an efficient way to use the data annotations described in the documentation in Models and the first code migrations in EF Core and SQL Server? OR is it just an [Timestamp]

annotation that will be available at this time?

My project uses tool Microsoft.EntityFrameworkCore.Tools

version "1.0.0-preview2-final" and Microsoft.EntityFrameworkCore

both Microsoft.EntityFrameworkCore.SqlServer

version "1.1.0".

Thanks for any help you can provide.

+1


source to share


1 answer


In order to have DateTime

model properties set in actions INSERT

and UPDATE

, I used a combination of Defaults via Fluent API

configuration and database triggers. The annotations I mentioned in my question absolutely do not configure SQL Server to generate standard or updated values DateTime

.

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

      

Thank!

0


source







All Articles