I'm using EntityFramework with ASP.Net MVC project I have 3 projects in my solution :
I have 2 class :
When I want to create Folder I want Id User to associate User with the folder. So in my class Folder I have this attribut to make relation :
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.'
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)
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. It seems you have only one, since you call it "_dbSet". I suggest you name one DbSet "Users" and one DbSet "Folders". Then you can easily access users and folders with one context.
Here is the code in 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#:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.