您很可能将对象保留在周围并使上下文膨胀。您可以通过使用任务管理器并观察内存使用情况来证明这一点。它的规模可能会越来越大。
如果您不再需要这些对象,请在完成后立即将它们从上下文中分离出来。您可以使用存储库很容易地做到这一点。
首先,分离它们的代码......
GenericRepository<Path> repo = new GenericRepository<Path>(context);
repo.Detach(item);
接下来,通用存储库...
public class GenericRepository<T> : IRepository<T>
where T : class
{
protected DbSet<T> DbSet { get; set; }
protected DbContext Context { get; set; }
public GenericRepository(DbContext context)
{
if (context == null)
{
throw new ArgumentException("An instance of DbContext is " +
"required to use this repository.", "context");
}
this.Context = context;
this.DbSet = this.Context.Set<T>();
}
public IQueryable<T> GetAll()
{
return this.DbSet;
}
public T GetById(int id)
{
return this.DbSet.Find(id);
}
public void Add(T entity)
{
DbEntityEntry entry = this.Context.Entry(entity);
if (entry.State != EntityState.Detached)
{
entry.State = EntityState.Added;
}
else
{
this.DbSet.Add(entity);
}
}
public void Update(T entity)
{
DbEntityEntry entry = this.Context.Entry(entity);
if (entry.State == EntityState.Detached)
{
this.DbSet.Attach(entity);
}
entry.State = EntityState.Modified;
}
public void Delete(T entity)
{
DbEntityEntry entry = this.Context.Entry(entity);
if (entry.State != EntityState.Deleted)
{
entry.State = EntityState.Deleted;
}
else
{
this.DbSet.Attach(entity);
this.DbSet.Remove(entity);
}
}
public void Delete(int id)
{
var entity = this.GetById(id);
if (entity != null)
{
this.Delete(entity);
}
}
public void Detach(T entity)
{
DbEntityEntry entry = this.Context.Entry(entity);
entry.State = EntityState.Detached;
}
}
我希望这有帮助。