How to use ValueGeneratedOnUpdate() correctly?

前端 未结 1 1561
夕颜
夕颜 2020-12-11 03:27

I\'m using EF Core 2.1.0-preview1-final CF approach with a MS SQL Server 2014 and want to set on-update a time stamp in one column automati

相关标签:
1条回答
  • 2020-12-11 03:37

    The Generated values documentation topic (the link mentioned in the question) contains the following Warning:

    How the value is generated for added and updated entities will depend on the database provider being used. Database providers may automatically setup value generation for some property types, while others will require you to manually setup how the value is generated.

    For example, when using SQL Server, byte[] properties that are set as generated on add or update and marked as concurrency tokens, will be setup with the rowversion data type - so that values will be generated in the database. However, if you specify that a DateTime property is generated on add or update, then you must setup a way for the values to be generated. One way to do this, is to configure a default value of GETDATE() (see Default Values) to generate values for new rows. You could then use a database trigger to generate values during updates (such as the following example trigger).

    followed by example trigger code.

    So basically you are expected to create trigger for value generation on update. EF Core will just read back the value from the database after updating the record (similar to identity and calculated columns).

    In your example, modify the generated migration Up method as follows:

    migrationBuilder.CreateTable(
        name: "Person",
        columns: table => new
        {
            Id = table.Column<int>(nullable: false)
                .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
            InsertDateTimeUtc = table.Column<DateTime>(nullable: false, defaultValueSql: "GETUTCDATE()"),
            Name = table.Column<string>(nullable: false),
            UpdateDateTimeUtc = table.Column<DateTime>(nullable: false, defaultValueSql: "GETUTCDATE()")
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Person", x => x.Id);
        });
    
    // Add the following:   
    migrationBuilder.Sql(
    @"CREATE TRIGGER [dbo].[Person_UPDATE] ON [dbo].[Person]
        AFTER UPDATE
    AS
    BEGIN
        SET NOCOUNT ON;
    
        IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN;
    
        DECLARE @Id INT
    
        SELECT @Id = INSERTED.Id
        FROM INSERTED
    
        UPDATE dbo.Person
        SET UpdateDateTimeUtc = GETUTCDATE()
        WHERE Id = @Id
    END");
    
    0 讨论(0)
提交回复
热议问题