简体   繁体   English

使用ADO.NET实体框架时出错

[英]Error Using ADO.NET Entity Framework

I want to convert a list to EntityCollection. 我想将列表转换为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. 无法将该对象添加到EntityCollection或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. 无法将附加到ObjectContext的对象添加到与源对象不关联的EntityCollection或EntityReference中。

Anyone know about this error? 有人知道这个错误吗?

It sounds like x is the result of an ObjectContext query. 听起来x是ObjectContext查询的结果。 Each ObjectContext tracks the entities it reads from the database to enable update scenarios. 每个ObjectContext跟踪从数据库读取的实体,以启用更新方案。 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. 术语是实体附加到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. 在您的情况下, x中的实体仍附加到实现它们的ObjectContext上,因此您不能将它们同时添加到另一个EntityCollection中。

You may be able to do that if you first Detach them, but if you do that, the first ObjectContext stops tracking them. 如果首先Detach它们,您也许可以这样做,但是如果这样做,则第一个ObjectContext停止跟踪它们。 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. 如果您不再希望再次更新这些项目,那不是问题,但是如果以后需要更新它们,则必须再次Attach它们。

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. 在这里,您创建了一个与对象上下文不关联的EntityCollection,因此不能向其添加其他对象。 They must first be attached to the object context. 它们必须首先附加到对象上下文。

Really what you probably want is to return IQueryable instead of IList. 您可能真正想要的是返回IQueryable而不是IList。 That would allow you to execute queries against the results of methodcall() . 这将允许您针对methodcall()的结果执行查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM