Timestamp in C# for persistence in Sqlserver

Asked

Viewed 86 times

1

Is there any typing that already treats this in C# to perform persistence in Sqlserver database?

I need to resolve the Createdat and Updatedat property. For each change, it will be stored in the database.

public class UserBaseEntity
{
    [Key]
    [ScaffoldColumn(false)]
    public int Id { get; set; }

    [Timestamp]
    public DateTime CreatedAt { get; set; }

    public DateTime UpdatedAt { get; set; }
}

The signature on the property would solve this case?

1 answer

1


You can use the type Byte[], following Microsoft’s own standard.

[Timestamp]
public Byte[] CreatedAt { get; set; }

Defining the type of your field as Byte[] and using the attribute [Timestamp] it will be recorded with the SQL Server rowversion (timestamp).

timestamp is synonymous with the type of rowversion data and is subject to behavior synonymous with data type. In DDL instructions, use rowversion instead of timestamp whenever possible. To get more information, see Data type synonyms (Transact-SQL).

Updating the database with the parameter -Verbose you will have the following SQL to generate the table (changing only its field CreatedAt as shown above):

CREATE TABLE [dbo].[UserBaseEntities] (
    [Id] [int] NOT NULL IDENTITY,
    [CreatedAt] rowversion NOT NULL,
    [UpdatedAt] [varbinary](max),
    CONSTRAINT [PK_dbo.UserBaseEntities] PRIMARY KEY ([Id])
)
  • I use for both Createat and Updateat, right?

  • 1

    Yes @Thiagocunha, I didn’t add why you didn’t add [Timestamp] to this field so I wasn’t sure if you wanted it this way either.

  • Vlw... Thank you! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.