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
xis 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
xare 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
Detachthem, 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 toAttachthem again.