Error Using ADO.NET Entity Framework
I want to convert a list to EntityCollection.
List<T> x = methodcall();
EntityCOllection<T> y = new EntityCollection<T>();
foreach(T t in x)
y.Add(t);
I get this error.
The object could not be added to the 开发者_开发知识库 EntityCollection or EntityReference. An object that is attached to an ObjectContext cannot be added to an EntityCollection or EntityReference that is not associated with a source object.
Anyone know about this error?
It sounds like x
is the result of an ObjectContext query. Each ObjectContext tracks the entities it reads from the database to enable update scenarios. It tracks the entities to know when (or if) they are modified, and which properties are modified.
The terminology is that the entities are attached to the ObjectContext. In your case, the entities in x
are still attached to the ObjectContext that materialized them, so you can't add them to another EntityCollection at the same time.
You may be able to do that if you first Detach
them, but if you do that, the first ObjectContext stops tracking them. If you never want to update those items again, it's not a problem, but if you later need to update them, you will have to Attach
them again.
Basically all entity objects are controlled by an object context which serves as change tracker. The idea here is that the entities themselves are dumb to their environment, but the object context knows what's going on.
This is an inversion of the DataSet model where the tables track their own changes.
So objects are added to an object context and its entity collections directly. Here you've created an EntityCollection that's not associated with an object context and therefore can't have other objects added to them. They must first be attached to the object context.
Really what you probably want is to return IQueryable instead of IList. That would allow you to execute queries against the results of methodcall()
.
精彩评论