Error Using ADO.NET Entity Framework

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-21 11:45:14

问题


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?


回答1:


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.




回答2:


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().



来源:https://stackoverflow.com/questions/2382161/error-using-ado-net-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!