title: Entity Framework/SQL2008 - How to Automatically Update LastModified fields for Entities?
body: <p>If i have the following entity:</p>
  
  <pre><code>public class PocoWithDates
  {
     public string PocoName { get; set; }
     public DateTime CreatedOn { get; set; }
     public DateTime LastModified { get; set; }
  }
  </code></pre>
  
  <p>Which corresponds to a SQL Server 2008 table with the same name/attributes...</p>
  
  <p>How can i <strong>automatically</strong>:</p>
  
  <ol>
  <li>Set the CreatedOn/LastModified field for the record to <strong>now</strong> (when doing INSERT)</li>
  <li>Set the LastModified field for the record to <strong>now</strong> (when doing UPDATE)</li>
  </ol>
  
  <p>When i say <strong>automatically</strong>, i mean i want to be able to do this:</p>
  
  <pre><code>poco.Name = "Changing the name";
  repository.Save(); 
  </code></pre>
  
  <p>Not this:</p>
  
  <pre><code>poco.Name = "Changing the name";
  poco.LastModified = DateTime.Now;
  repository.Save();
  </code></pre>
  
  <p>Behind the scenes, "something" should automatically update the datetime fields. What is that "something"?</p>
  
  <p>I'm using Entity Framework 4.0 - is there a way that EF can do that automatically for me? (a special setting in the EDMX maybe?)</p>
  
  <p>From the SQL Server side, i can use <strong>DefaultValue</strong>, but that will only work for <strong>INSERT's</strong> (not UPDATE's).</p>
  
  <p>Similarly, i can set a default value using a constructor on the POCO's, but again this will only work when instantiating the object.</p>
  
  <p>And of course i <strong>could</strong> use Triggers, but it's not ideal.</p>
  
  <p>Because i'm using Entity Framework, i can hook into the <strong>SavingChanges</strong> event and update the date fields here, but the problem is i need to become "aware" of the POCO's (at the moment, my repository is implemented with generics). I would need to do some sort of OO trickery (like make my POCO's implement an interface, and call a method on that). I'm not adversed to that, but if i have to do that, i would rather manually set the fields.</p>
  
  <p>I'm basically looking for a SQL Server 2008 or Entity Framework 4.0 solution. (or a smart .NET way)</p>
  
  <p>Any ideas?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Thanks to @marc_s for his answer, but i went with a solution which is better for my scenario.</p>