1

I am using EF 5.0 in a WinForms application. I dispose the DBContext quick.

Nevertheless I must maintain a static list of Customer entities , which I populate on startup using a DBContext - again, disposed quickly. Plus, I slighlty use multi-threading in some parts of the application.

The issue is that I receive this exception every once and then:

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

Should I detach every Customer in that static list before disposing the DBContext? Should I use some other design for a WinForms application? I appreciate your feedback.

4

3 回答 3

2

Try use AsNoTracking method when querying instances: http://msdn.microsoft.com/en-us/library/gg679352(v=vs.103).aspx

于 2013-05-20T19:16:56.620 回答
2

Consider building Data Transfer Objects to make a clean separation between EF and the static list.

The main benefit of this is limiting EF's influence on the rest of the application.

于 2013-05-20T19:29:20.140 回答
1

I would not use a list of Customer entity objects, but some mirror type, say CustomerListItem.

You can populate the list by projecting Customers into the items

db.Customers.Select(c => new CustomerListItem { Name = c.Name, ... })

By doing this you create objects that are not tracked. And you will be sure that changes in the entity model will not affect other parts of the application that depend on the customer list. And you will not run into potential lazy loading exceptions (if Customer has lazy navigation properties).

As it is a static list accessible to the whole application I would use a ReadOnlyCollection.

于 2013-05-20T19:33:29.030 回答