Geeks With Blogs

News Please visit me at my new blog!!

profile for Aligned at Stack Overflow, Q&A for professional and enthusiast programmers
"free in Christ Jesus from the law of sin and death." Romans 8:2 (ESV) Check out the Falling Plates video on YouTube.
more about the Gospel
And then listen to Francis Chan speaking at LifeLight in SD.



Programming and Learning from SD

I have database tables that have DateCreated and DateModified as DateTime types. I was getting the error (“The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.”) when I tried to save through the context.SaveChanges() for Entity Framework.

First I added GetGETUTCDATE() to the default of the column in the database.

Then in my Repository Update Method, I used reflection to set the DateModified property.

public void Update(T entity)
{
  var entry = this._context.Entry(entity);
  if (entry.State == EntityState.Detached)
  {
    this._set.Attach(entity);
    entry.State = EntityState.Modified;
  }

  // update the DateModified if the entity has it
  // DateCreated and DateModified should be defaulted in the Database
  // you'll get 'The conversion of a datetime2 data type to a date time data type resulted in an out-of-range value.' if you don't set those values.
  var type = entity.GetType();
  var property = type.GetProperty("DateModified");
  if (property != null)
  {
    property.SetValue(entity, DateTime.UtcNow, null);
  }

  this.SaveChanges();
}

These fixes the problem and it seems like a good approach to me.

EDIT: Another way to do this without reflection:

Create an in interface.

public interface IAudit
{
  /// <summary> Gets or sets the modified date.</summary>
  /// <value> The date modified.</value>
  DateTime DateModified { get; set; }
}

Then in a partial class of the entity (since the entity is generated) implement this interface on all your entities that have the DateModified or other fields.

public partial class Contact : IAudit
    {
    }

Then the DBContextRepository update method becomes:

public void Update(T entity)
{
  var entry = this._context.Entry(entity);
  if (entry.State == EntityState.Detached)
  {
    this._set.Attach(entity);
    entry.State = EntityState.Modified;
  }
  
   var audit = entity as IAudit;
  if (audit != null)
  {
    audit.DateModified = DateTime.UtcNow;
  }

  this.SaveChanges();
}
Posted on Thursday, January 10, 2013 4:01 PM Entity Framework | Back to top


Comments on this post: Set the DateModified in the Repository

# Thanks
Requesting Gravatar...
Thank you for this post. In order to implement IAuditable I was thinking of modifying the templates used to generate the entity classes from my edmx, but your blog made me realize that i could just simply add a file containing the same partial classes with any interface i'd want.
Left by alpha pecap on Jun 04, 2013 2:39 PM

Your comment:
 (will show your gravatar)


Copyright © Aligned | Powered by: GeeksWithBlogs.net