Reputation: 17930
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 ?
Upvotes: 0
Views: 330
Reputation: 17930
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.
Upvotes: 0
Reputation: 8152
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.
Upvotes: 0
Reputation: 5567
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'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()
Upvotes: 1