0

I am creating tables using code first and I have column called CreatedDate, I want this column to have a default value of GETDATE().

But I don't want to do this is in the migration script like below

AddColumn("Agents", "CreatedDate", n => n.DateTime(nullable: false, defaultValueSql: "GETDATE()"));

How can I do this in the Mapping or in the model class?

leppie
  • 115,091
  • 17
  • 196
  • 297
TTK
  • 33
  • 6

1 Answers1

1

Well you need to set the default value in the POCO, you can set it in the property backing field or in the constructor as follow.

1. Constructor

public class Agent
{
    public Agent()
    {
        CreatedDate = DateTime.Now;
    }

    public DateTime CreatedDate { get; set; }
}

2. Property Backing Field

public class Agent
{
    private DateTime _createdDate;
    public DateTime Date
    {
        get { return _createdDate == default(DateTime) ? DateTime.Now : _createdDate; }
        set { _createdDate = value; }
    }
}
Community
  • 1
  • 1
Yuliam Chandra
  • 14,494
  • 12
  • 52
  • 67