Set default value for date and time using PetaPoco

I have a PetaPoco class that defines a database table. It looks like this:

namespace MyProject.Pocos { [TableName("AdminNotification")] [PrimaryKey("id", autoIncrement = true)] [ExplicitColumns] public class AdminNotification { [Column("id")] [PrimaryKeyColumn(AutoIncrement = true)] public int id { get; set; } [Column("dateTime")] public DateTime dateTime { get; set; } [Column("adminNotificationTypeId")] public int adminNotificationTypeId { get; set; } } } 

It works fine, except for one. In the database table itself (in SQL Server Express), the default value for "dateTime" is set - by default it is (getdate()) . However, when a record is inserted using the PetaPoco class in my code, the dateTime value is always NULL.

How to set default value in PetaPoco class to current date / time?

Thanks!

+1
source share
1 answer

One way is to add a constructor and set the default value there:

  [TableName("AdminNotification")] [PrimaryKey("id", autoIncrement = true)] [ExplicitColumns] public class AdminNotification { [Column("id")] [PrimaryKeyColumn(AutoIncrement = true)] public int id { get; set; } [Column("dateTime")] public DateTime dateTime { get; set; } [Column("adminNotificationTypeId")] public int adminNotificationTypeId { get; set; } public AdminNotification(){ dateTime = DateTime.Now; } } 

Depending on the method of creating and inserting the object, the value will show the creation time of AdminNotification, and not the time that it was actually written to the database, but most of the time the difference is insignificant and “Make the difference” is won.

0
source

Source: https://habr.com/ru/post/981277/


All Articles