Error using ADO.NET Entity Framework

I want to convert a list to an EntityCollection.

List<T> x = methodcall(); EntityCOllection<T> y = new EntityCollection<T>(); foreach(T t in x) y.Add(t); 

I get this error.

An object cannot be added to an EntityCollection or EntityReference. An object attached to an ObjectContext cannot be added to an EntityCollection or EntityReference which is not associated with the source object.

Does anyone know about this error?

+4
source share
2 answers

It appears that x is the result of an ObjectContext query. Each ObjectContext keeps track of the objects that it reads from the database to enable update scripts. It tracks entities to know when (or if) they were changed, and what properties were changed.

The terminology is that entities are bound to an ObjectContext. In your case, the objects in x are still bound to the materialized ObjectContext, so you cannot add them to another EntityCollection at the same time.

You may be able to do this if you first Detach them, but if you do, the first ObjectContext will stop tracking them. If you never want to update these elements again, this is not a problem, but if you need to update them, you will have to Attach them again again.

+2
source

Basically, all entity objects are controlled by the context of the object, which serves as change tracking. The idea here is that the entities themselves are unthinkable in their environment, but the context of the object knows what is happening.

This is the inverse of the DataSet model, in which tables track their own changes.

Thus, objects are added directly to the context of an object and its collection of entities. Here you created an EntityCollection that is not related to the context of the object and therefore cannot add other objects to them. First they must be attached to the object.

Indeed, you probably want to return an IQueryable instead of an IList. This will allow you to execute queries on the results of methodcall() .

0
source

Source: https://habr.com/ru/post/1303157/


All Articles