Reputation: 1
I am working on asp.net mvc-4 web application and i am using entity framework 5.0. now I have mapped my database tables using ado.net entity framework , which generated a .edmx file and DBContext class.
now i am not sure how does asp.net mvc handle the following scenario:-
I have a repository model class which directly interact with the database entities , as follow:-
public class Repository
{
private MyEntities my = new MyEntities();
public void Save()
{
my.SaveChanges();
}
Also I have the following Controller class, which initiate the above repository and another API repository class , as follow:-
public class ServerController : Controller
{
Repository repository = new Repository();
APIRepository APIrepository = new APIRepository();
//code goes here
Public ActionResult Create(Emp e)
{
//code goes here..
var result = APIreposioty.SendCall(...);
repository.Save();
}
The APIRepositoty also initiate the repository, as follow:-
public class APIRepository
{
Repository repository = new Repository();
so now inside my controller class i have the following:-
so now when i call the repositoty.Save() inside the action method? will it saves the entity object inside the repositry & inside the APIrepository ? or there will be two separate context objects being managed by the user session? and they do not interfere with each other ?
Upvotes: 1
Views: 316
Reputation: 9854
Your controller ends up creating distinct instances of your entity context. They are not bound in any way. A save on one of them will only save the entities it has loaded/registered as added. Entities handled by the other one will not be saved.
For your case, an usual pattern for handling that is to use dependency injection. Configure it for instantiating only one DBContext
per controller, whatever the number of repositories the controller uses (directly or through other dependencies).
Upvotes: 1