Note that there are some explanatory texts on larger screens.

plurals
  1. POAdding CreatedDate to an entity using Entity Framework 5 Code First
    text
    copied!<p>I am trying to add a <code>CreatedDate</code> property to entities in my Model and am using EF5 Code First. I want this date to not be changed once set, I want it to be a UTC date. I do NOT want to use a constructor, as I have many entities in my model that I want to inherit from an abstract class containing the <code>CreatedDate</code> property, and I can't enforce a constructor with an interface.</p> <p>I have tried different data annotations and I have attempted to write a database initializer that would pick up a specific entity type and write an alter constraint with a <code>getdate()</code> default value for the correct <code>table_name</code> and <code>column_name</code>, but I have not been able to write that code correctly.</p> <p>Please do not refer me to the <a href="http://auditdbcontext.codeplex.com/SourceControl/changeset/view/18413#215563" rel="nofollow noreferrer">AuditDbContext - Entity Framework Auditing Context</a> or the <a href="https://github.com/loresoft/EntityFramework.Extended" rel="nofollow noreferrer">EntityFramework.Extended</a> tools, as they do not do what I need here.</p> <p><strong>UPDATE</strong></p> <p>My <code>CreatedDate</code> is null on <code>SaveChanges()</code> because I am passing a ViewModel to my view, which correctly has no audit property called <code>CreatedDate</code> in it. And even if I passed the model to my view, I am not editing or storing the <code>CreatedDate</code> in the view.</p> <p>I read <a href="https://stackoverflow.com/questions/6564772/ef-code-first-readonly-column">here</a> that I could add the <code>[DatabaseGenerated(DatabaseGeneratedOption.Identity)]</code> and this would tell EF to store the <code>CreatedDate</code> correctly after Insert and Update, but not allow it to be changed by my application: but I just get a <code>Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF</code> error by adding this attribute.</p> <p>I am about to switch to EF Model First because this simple database requirement is ridiculous to implement in Code First.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload