0

I have added a database repository layer to my MVC application which does the CRUD. Sometimes my controllers need to call multiple db repositories and I do this by calling the db respitories I need. This in turn creates multiple db context objects. One for each repository. Should there be multiple db context objects or should I pass in a single db context to the repository object?

2 Answers 2

1

In your controller you should use one dbContext. Because When you try to update your model in db, you may get error. Because of different dbContext.

Check HERE

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help. This works a treat! Now I have to go through all my code and change it.
1

There should be only one, I highly recommend using Unit of Work pattern:

Here's a quick and simple example:

public interface IUoW : IDisposable
{
    MyDbContext DbContext { get; set; }  

    void SaveChanges();
}

public class UoW : IUoW
{
    public MyDbContext DbContext { get; set; }

    public UoW()
    {
        DbContext = new MyDbContext();
    }

    public void SaveChanges()
    {
        DbContext.SaveChanges();
    }

    public void Dispose()
    {
        DbContext.Dispose();
    }
}

You need to instantiate UoW once for each request and pass it to your repository:

public class MyRepository
{
    private MyDbContext _context;

    public MyRepository(IUoW uow)
    {
        _context = uow.MyDbContext;
    }

    // your crud methods
}

Of course it's just a very simple example of it and I've seen people implement this pattern in many different ways.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.