Mohamed Ahmed Mohamed Ahmed - 1 month ago 8
C# Question

EF: Is it OK to use default value for the created date property?

I want to set the

CreatedDate
column to the current datetime whenever a new row is inserted, so I made it like this:

public DateTime CreateDate { get; set; } = DateTime.Now;


I tested it and it works just fine, Is this a practical approach? I saw many articles achieve the same with so much code and using fluent API, no one mentioned this simple method?

hvd hvd
Answer

That depends on what you want to accomplish.

I saw many articles achieve the same with so much code and using fluent API,

Most of those articles will be about adding default values at the database level. You're not doing that. If you insert a row into your table using plain SQL, and don't specify a value for CreatedDate, you'll get an error.

With what you're doing, CreatedDate always needs to be specified in SQL when inserting. But Entity Framework will always specify it in the SQL when inserting, and completely ignore any default value set at the database level.

So if that's what you want -- the default value only gets applied when creating objects through C# -- then what you're doing is totally fine. It may also be written as setting the value from inside the class's constructor.

@Alex Kozlowski raises a good comment though, which is that DateTime.Now may not be the value you expect to be inserted. It depends on which system is running the code. The time zone may be different from your server's, or the clock may be out of sync.