简体   繁体   English

EF 4似乎无法调用SaveChanges

[英]EF 4 can't seem to call SaveChanges

I have this Context with the following method override : 我有以下方法覆盖此上下文:

  public class MyContext : DbContext
  { 
    public DbSet<Contract> Contracts{get;set;}  
    public override int SaveChanges()
    {
        Contract ctr = new Contract
        {
            ContractId = "CT99999991",
            ContractNumber = "9000",
            LastModifiedDate = DateTime.Now,
            GracePeriod = DateTime.Now,
            ShipByDate = DateTime.Now,
            ExpirationDate = DateTime.Now
        };
        this.Contracts.Add(ctr);
        return base.SaveChanges();
    }
  }

No matter what I tried, I never succeed in making this part of the code succeed. 无论我尝试了什么,我都不会成功使这部分代码成功。 I would love to save the upper Contract in the database on SaveChanges event occurence. 我希望在发生SaveChanges事件时将上层合同保存在数据库中。 Is there something I'm overlooking ? 我有什么要注意的吗?

This isn't something I've tried to do myself, but it's possible that because you're inside the SaveChanges() method already, the context's changelist has already been created. 这不是我自己尝试做的事情,但是可能因为您已经在SaveChanges()方法内部,所以上下文的更改列表已经创建。 So when you add your new Contract to the context's Contracts collection, you would have to make your context rebuild its list of changes that need to be persisted back to the database before calling base.SaveChanges() 因此,当您将新的Contract添加到上下文的Contracts集合中时,您将必须使上下文重建其更改列表,这些更改列表需要在调用base.SaveChanges()之前保留回数据库。

What you should instead do is to hook into the SavingChanges event of the ObjectContext . 相反,您应该挂入ObjectContextSavingChanges事件 This will allow you to save to an archive/audit table. 这将允许您保存到存档/审核表。 Here is an article that explains how to do it. 这是一篇文章 ,说明如何执行此操作。 I've done this before and it works really well. 我以前做过,而且效果很好。

I was hooking into the custom Context class ( class MyContext : DbContext ) and it wasn't working. 我迷上了自定义Context类(类MyContext:DbContext),但是它没有用。

I finally resorted to hooking into the WCF Data Service class (class MyDataService : DataService ) and it works well. 最后,我求助于加入WCF数据服务类(类MyDataService:DataService),并且效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM