0

How can I do to call a unique SaveChanges to affect all changes in all repositories that I use? Should I create a class that contains all repositories and a Save method? What's the best way to do it?


I'm trying this:

public ActionResult Create()
{
    Product Product = new Product() { Id = 1, Name = "test", Amount = 1 };

    if (_productService.Insert(Product))
    {
        context.SaveChanges();

        return View();
    }

    return RedirectToAction("Index");
}

Is this correct?

MuriloKunze
  • 15,195
  • 17
  • 54
  • 82

2 Answers2

0

The best way is called unit of work and it is generally wrapper class to your EF context which is passed to constructor of your repositories. You than call Save on this new class.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • So I need to create a instance of Entitie(inherited from DbContext), pass it to a repository and then call entitie.SaveChanges? – MuriloKunze Apr 17 '12 at 19:18
  • No you call save changes outside of the repository. Repository is not responsible for saving data, it is responsibility of the new context wrapper. – Ladislav Mrnka Apr 17 '12 at 19:23
  • I update the problem's description.. can you tell me if this is right? – MuriloKunze Apr 17 '12 at 19:33
  • I need some validations before insert.. so I create a service layer passing the context to constructor. – MuriloKunze Apr 17 '12 at 19:41
  • @Peri: Yes [context is unit of work and DbSet / ObjectSet is repository](http://stackoverflow.com/questions/5625746/generic-repository-with-ef-4-1-what-is-the-point/5626884#5626884). – Ladislav Mrnka Apr 17 '12 at 21:40
0

Pass IDbContext/ObjectContext to constructor of your repositories. Work with repositories and call Save on context not on repository.

I would also rethink if You need repositories at all.

Piotr Perak
  • 10,718
  • 9
  • 49
  • 86
  • Yeah, I see Ladislav saying that repository isn't good.. I need some validations before save data.. so, what about I use only a service layer and inside it I call IDbContext methods? is this good? – MuriloKunze Apr 17 '12 at 19:40