Set default datetime value with PetaPoco

半世苍凉 提交于 2019-12-24 11:34:59

问题


I have a PetaPoco class which 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 great except for one thing. In the database table itself (in SQL Server Express) there is a default value set for 'dateTime' - it defaults to (getdate()). However, when record is inserted using the PetaPoco class in my code, the value of dateTime is always NULL.

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

Thanks!


回答1:


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 way you create and insert the object, the value will be showing the time of creation of the AdminNotification, not the time it has actually been written to the database, but most of the time the difference is negligible and won't make a difference.



来源:https://stackoverflow.com/questions/22457887/set-default-datetime-value-with-petapoco

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!