![](/img/trans.png)
[英]C# Entity Framework “An entity object cannot be referenced by multiple instances of IEntityChangeTracker”
[英]C# Entity Framework - IEntityChangeTracker issue
我收到的異常是IEntityChangeTracker的多個實例無法引用實體對象 。 我的代碼結構如此......
我的上下文類看起來像這樣:
public class MyContext : DbContext, IDataContext
{
public MyContext (string connectionString) :
base(connectionString)
{
}
public DbSet<AssigneeModel> Assignees { get; set; }
public DbSet<AssetAssignmentModel> AssetAssignments { get; set; }
}
public class AssigneeController : Controller
{
protected MyContext db = new MyContext(ConnectionString);
[HttpPost]
public ActionResult Import(SomeObjectType file)
{
AssigneeModel assignee = new AssigneeModel();
assignee.FirstName = "Joe";
assignee.LastName = "Smith";
// Assignees have assets, and the relationship is established via an AssetAssignmentModel entity
AssetAssignmentModel assetAssignmentModel = new AssetAssignmentModel
{
Asset = someExistingAsset,
// Assignee = assignee, // Don't establish relationship here, this object will be added to the assignee collection
}
assignee.AssetAssignments.Add(assetAssignmentModel); // Manually add object to establish relationship
db.Assignees.Add(assignee); // Add the assignee object
// Exception occurs when adding the object above
};
}
EF版本4.1
你已經將它標記為EF4.1(我希望代碼優先和dbcontext),但它看起來像EntityObject(edmx,objectcontext,VS2008和VS2010中的默認代碼gen)的副作用。
在這種情況下,如果您有一個實體(派生自EntityObject)並且您在沒有首先分離實體的情況下處置其上下文,則實體實例仍然具有該上下文的工件。 因此,當您嘗試將其附加到另一個上下文時,它會給出此消息。 如果您不使用POCO,那么EF 3.5和EF4會出現問題。 我很長時間沒有和它搏斗,但我記得那個刺痛。 :)
問題來自您的Asset對象,當您從其他方法獲取它時,在將其添加到此新上下文之前,您需要將其從該上下文中顯式分離。 正如Julie所提到的,實體實例將攜帶上下文,但是問題不是你創建的AssigneeModel
,而是你檢索到的someExistingAsset
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.