Solve the problem of "entity objects are referenced by multiple IEntityChangeTracker instances" in Entity Framework 4.1
When saving an entity that contains an entity reference using Entity Framework 4.1, you may encounter the exception "ADO.Net Entity Framework entity object cannot be referenced by multiple IEntityChangeTracker instances." This exception typically occurs when multiple Entity Framework contexts manage the same entity.
For example, in the code snippet, the two service classes EmployeeService
and CityService
create their own context instances respectively. When a city1
entity is retrieved from CityService
, it is attached to the context of CityService
. Later, when the e1
employee entity is created and its reference is assigned to city1
, both entities are added to the context of EmployeeService
.
As a result, city1
is attached to two different contexts, causing the exception.
Solution:
Method 1: Use a single context
Create a single context instance and inject it into two service classes EmployeeService
and CityService
:
<code class="language-csharp">var context = new YourDbContext(); // 创建单例上下文 EmployeeService es = new EmployeeService(context); CityService cs = new CityService(context); // 使用相同的上下文实例</code>
Method 2: Merge Services
Consolidate related entities into a single service, which is responsible for all entity interactions. This approach simplifies the manipulation of relationships between entities.
With the above method, you can avoid the exception "The entity object cannot be referenced by multiple IEntityChangeTracker instances" and successfully save the entity containing the entity reference.
The above is the detailed content of How to Resolve the 'Entity Object Referenced by Multiple Instances of IEntityChangeTracker' Exception in Entity Framework 4.1?. For more information, please follow other related articles on the PHP Chinese website!