[英]Entity Framework System.InvalidOperationException : 'An entity object cannot be referenced by multiple instances of IEntityChangeTracker.'
I'm using EntityFramework with ASP.Net MVC project I have 3 projects in my solution : 我在ASP.Net MVC项目中使用EntityFramework,我的解决方案中有3个项目:
I have 2 class : 我有2节课:
When I want to create Folder I want Id User to associate User with the folder. 当我要创建文件夹时,我希望ID用户将用户与文件夹相关联。 So in my class Folder I have this attribut to make relation : 所以在我的班级Folder中,我有这个属性来建立关系:
public virtual User user {get; set; }
When I want to add folder in DB I have an error at this line : 当我想在数据库中添加文件夹时,在此行出现错误:
_dbSet.Add(entity);
Error is : System.InvalidOperationException : 'An entity object cannot be referenced by multiple instances of IEntityChangeTracker.' 错误是: System.InvalidOperationException:'一个IEntityChangeTracker的多个实例不能引用一个实体对象。
This is the method 这是方法
public void Insert(TEntity entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
try
{
_dbSet.Add(entity);
_dbContext.SaveChanges();
}
catch (DbEntityValidationException ex)
{
ThrowValidationError(ex);
}
}
I think I don't use the same DbContext but I don't know how keep the same DbContext when I use many entities (User and Folder) 我想我没有使用相同的DbContext,但是当使用许多实体(用户和文件夹)时,我不知道如何保持相同的DbContext
I try to answer your last question. 我试着回答你的最后一个问题。
I think I don't use the same DbContext but I don't know
how keep the same DbContext when I use many entities (User and Folder)
Your Context can have multiple DbSet. 您的上下文可以具有多个DbSet。 It seems you have only one, since you call it "_dbSet". 似乎只有一个,因为您将其称为“ _dbSet”。 I suggest you name one DbSet "Users" and one DbSet "Folders". 我建议您命名一个DbSet“用户”和一个DbSet“文件夹”。 Then you can easily access users and folders with one context. 然后,您可以轻松地通过一种上下文访问用户和文件夹。
Here is the code in VB.net: 这是VB.net中的代码:
Public Class MyContext
Inherits DbContext
Public Property Users As DbSet(of User)
Public Property Folders As DbSet(of Folder)
End Class
and c#: 和C#:
public class MyContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Folder> Folders { get; set; }
}
Please post the source code of your current context class, if you have more questions regarding this. 如果对此有更多疑问,请发布当前上下文类的源代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.