开发者

Entity Framework Code First, Unit of Work, Repository and shared DbContext

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开发者_Go百科; 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?


Based on the error message, you may need to detach an object from one context to save it in another. You could also construct a new object copied from the first (deep copy necessary here) in order to do that. There is also additional thought required to handle any foreign keys that don't have object reference counterparts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜