West Wind Web Toolkit for ASP.NET
Re: Updating entity - getting error
03/12/2010
02:23:02 PM
2VX0UTVTP Show this entire thread in new window
Gratar Image based on email address
From:
Rick Strahl
To:
Paul Mrozowski 
Attachments:
None

Yeah this stuff just doesn't work well with LINQ to SQL. The problem is that entities are tracked EVEN IF YOU CREATE A BRAND NEW INSTANCE of an entity. So even reloading an entity in many cases causes actually the same instance to be loaded up.

Attach and Detach doesn't really work for anything but single level instances in LINQ to SQL.

The trick is to stick with the single DataContext concept and deal with an entity at a time and completely dispose the context if you need new instances on the same thread to ensure you're getting completely cleean instances.

+++ Rick ---

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




Rick Strahl
West Wind Technologies

Where do you want to surf today?
Reader Version: 5.0

from Maui, Hawaii