5

在我的 EF 4.1 MVC3 Web 应用程序中创建新订单时,我需要自动插入当前日期。我还需要自动添加当前登录的用户——我正在使用表单身份验证。在网上搜索后,我发现我需要重写 SaveChanges() 函数,StackOverflow 上的一篇文章展示了如何做到这一点:Entity Framework 4.1 Automatic date。但是,我无法让代码工作。这段代码去哪儿了?我如何找出是什么?

对不起,如果这个问题是微不足道的 - 我是 EF 的新手。B.

4

1 回答 1

4

您可以在上下文类中覆盖,

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

另一个选项是您可以在实体的构造函数中设置默认值,

   Public class YourEntity{

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

      Public DateTime CreatedDate{get;set;}
   }
于 2012-04-24T15:07:48.267 回答