I have a "invoice" business object (ultimately inherits from the BusinessObjectLinq class). I have some code which adds/updates/deletes line items and saves the results. Then I create a new instance of invoice so I can do some tests on what just occurred (when I kept the existing instances Linq to Sql was trying to be helpful and kept returning a cached copy of the data). The code does the following:
var invoice = new InvoiceBizObj(); invoice.Load(pk); invoice.UpdateStatus(); // InvoiceBizObj class public void UpdateStatus() { this.UpdateStatus(this.Entity); } public void UpdateStatus() { var count = entity.InvoiceLines.Count(); var valid = this.Validate(entity); if (count > 0 && valid && entity.InvoiceStatus.Code == "IN") { entity.InvoiceStatus = this.Context.InvoiceStatus.Single(s => s.Code == "OP"); this.Save(entity); } }
The problem I'm running into is that Save() is failing with a "An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.". I originally tried just setting the foreign key directly, but it didn't like that. It failed with a "operation is not valid due to the current state of the object" error, which is why I replaced it with the .Single() call.
Thinking that maybe the entity.InvoiceLines.Count() was causing the problem I tested it by hardcoding the count to 1. Same error. I removed the check for entity.InvoiceStatus.Code in the "if" statement. Same error.
I know each business object creates its own DataContext but in this case I'm only dealing with one of them.
Anyone see what I'm missing?
-Paul