I'm building a web app using EF Code First and ASP.NET MVC. I have following types:
IProblemRepository
EFProblemRepository
ICategoryRepository
EFCategoryRepository
CleanStreets // db context
IUnitOfWork
// etc.
Code snippets :
public interface IUnitOfWork
{
void Save();
}
public class CleanStreets : DbContext, IUnitOfWork
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<Point> Points { get; set; }
public DbSet<Rating> Ratings { get; set; }
public DbSet<Picture> Pictures { get; set; }
public DbSet<Problem> Problems { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(u => u.Comments)
.WithRequired(c => c.User)
.HasForeignKey(c => c.UserID)
.WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
public void Save()
{
this.SaveChanges();
}
}
public class EFProblemRepository : IProblemRepository
{
private readonly CleanStreets data;
public EFProblemRepository(CleanStreets data)
{
this.data = data;
}
public void Save(Problem problem)
{
if (problem.ProblemID == 0)
{
data.Problems.Add(problem);
}
data.Save();
}
...
}
At first, I didn't have a UnitOfWork. I created a new context in every repository. But after I wanted to save a Problem
(Problem
includes Category
), using the Save method provided above, I received the following error:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker
I found, on stackoverflow, that the problem is with my db context and the solution was to create a shared context with the unit of work pattern. I tried to do that (as you can see above) but I still get the error. Every time when I want to store a Problem
the error pops. Did I implement a "shared" db context right?