Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly override the SaveChanges function in EF 4.1

I need to automatically insert the current date when I create a new order in my EF 4.1 MVC3 web application. I also need to automatically add the currently logged in user - I'm using forms authentication. After searching the web, I found that I need to override the SaveChanges() function and an article on StackOverflow showed how to do this: Entity Framework 4.1 Automatic date. However, I couldn't get the code to work. Where does this code go? How do I find out what is?

Sorry if the question is trivial - I'm new to EF. B.

like image 263
bearaman Avatar asked Oct 09 '22 00:10

bearaman


1 Answers

You can override in your context class,

public partial class YourDbContext: DbContext
    {
      public  YourDbContext()
        {               
        }
      public override int SaveChanges()
      {
       // do your additional stuff here.. (Ex:- save current user)
           return base.SaveChanges();
      }   
}

And the other option is you can set default values in the constructor of your entity,

   Public class YourEntity{

      public YourEntity(){
          CreatedDate=DateTime.Now;
      }

      Public DateTime CreatedDate{get;set;}
   }
like image 118
Jayantha Lal Sirisena Avatar answered Oct 12 '22 13:10

Jayantha Lal Sirisena