West Wind Web Toolkit for ASP.NET
Re: Updating entity - getting error
03/12/2010
10:59:57 AM
2VX0NKUIG Show this entire thread in new window
Gratar Image based on email address
From:
Matt Slay
To:
Paul Mrozowski 
Attachments:
None
One thing that I see that looks funny is that you are calling this.UpdateStatus(this.Entity); which passes a parameter, but I don't see where you have a method named UpdateStatus() that accepts a parameter. That alone should cause a compiler error.

Another matter... Why not use this.Save() rather than this.Save(entity)? Looking at the WW source code for the Save() method shows that any time you pass in a entity, it creates a new context, and then attempts to InsertOnSubmit() for new records, or Attach() for existing records then it calls SubmitChanges().

Why not just do a plain old Save()?

I need someone else to take a look at this code since I'm not seeing what the heck it's complaining about. I've followed various links explaining the error messages but it's not really clicking for me.

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