如何正确覆盖EF 4.1中的SaveChanges函数 [英] How to correctly override the SaveChanges function in EF 4.1

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

问题描述

我需要在我的EF 4.1 MVC3 Web应用程序中创建新订单时自动插入当前日期。我还需要自动添加当前登录的用户 - 我正在使用表单身份验证。
搜索网页后,我发现我需要覆盖SaveChanges()函数,而StackOverflow上的一篇文章显示了如何做到这一点:实体框架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?

对不起,如果问题很简单 - 我是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;}
   }

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

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