如何正确重写的SaveChanges功能EF 4.1 [英] How to correctly override the SaveChanges function in EF 4.1

查看:708
本文介绍了如何正确重写的SaveChanges功能EF 4.1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的时候我在EF 4.1 MVC3 Web应用程序创建新订单自动插入当前日期。我还需要自动添加当前登录的用户 - 我使用窗体身份验证。
在网上搜索后,我发现我需要覆盖的SaveChanges()函数,并在计算器上的一篇文章介绍了如何做到这一点:的实体框架4.1自动日期。但是,我不能得到code工作。
哪里该code去了?
我如何找出是什么?

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?

很抱歉,如果问题是微不足道的 - 我是新来的EF。
B点。

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

推荐答案

您可以在上下文类重写,

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;}
   }

这篇关于如何正确重写的SaveChanges功能EF 4.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆