Reputation: 1091
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.
Upvotes: 5
Views: 691
Reputation: 21366
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;}
}
Upvotes: 4