我有以下存储库结构:
public class Repository<T> where T : class
{
protected DataContext context = null;
protected DbSet<T> DbSet
{
get; set;
}
public Repository()
{
context = new DataContext();
DbSet = context.Set<T>();
}
public Repository(DataContext context)
{
this.context = context;
}
}
...
public class PlayerpostRepository : Repository<PlayerPost>
{
public PlayerpostRepository(DataContext context)
{
this.context = context;
}
}
...
public class PlayerRepository : Repository<Player>
{
public PlayerRepository(DataContext context)
{
this.context = context;
}
}
在我的控制器中,我创建了这样的实例:
private static DataContext db = new DataContext();
private PlayerpostRepository repository = new PlayerpostRepository(db);
private PlayerRepository playerrep = new PlayerRepository(db);
但是当我在控制器中调用repository.SaveChanges()
方法时,我收到以下错误:
实体对象不能被IEntityChangeTracker的多个实例引用
如果我理解正确的话,意味着我创建了多个DbContext
的实例,这些实例连接到一个对象。我不知道发生了什么。