EF 4 似乎无法调用 SaveChanges
我有这个上下文与以下方法覆盖:
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();
}
}
无论我尝试什么,我都没有成功地使这部分代码成功。 我希望在 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.
Is there something I'm overlooking ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是我自己尝试做的事情,但有可能因为您已经在 SaveChanges() 方法中,所以上下文的更改列表已经创建。因此,当您将新的
Contract
添加到上下文的Contracts
集合中时,您必须让上下文重建其需要在调用之前保留回数据库的更改列表base.SaveChanges()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. So when you add your new
Contract
to the context'sContracts
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()您应该做的是挂钩 SavingChanges ObjectContext 的事件。这将允许您保存到存档/审核表。 这里有一篇文章解释了如何执行此操作。我以前曾经这样做过并且效果非常好。
What you should instead do is to hook into the SavingChanges event of the ObjectContext. 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.
我正在连接自定义 Context 类(类 MyContext : DbContext ),但它不起作用。
我最终求助于 WCF 数据服务类(类 MyDataService : DataService )并且它运行良好。
I was hooking into the custom Context class ( class MyContext : DbContext ) and it wasn't working.
I finally resorted to hooking into the WCF Data Service class (class MyDataService : DataService ) and it works well.