First I was using a singleton class with only one instance of my entities (my context) but that means every user on the site uses that same instance, so I changed it to use a new instance per controller.
I've got my "UserController" and "CompanyController" (both used to update or get users/companies)
A User object has a link to Company.
What I do in my usercontroller:
1 public void addUser(UserDTO userDTO) {
2 User user = User.CreateUser(0, .....)
3 user.Company = new CompanyController().getCompany(userDTO.Company.companyId);
4 context.AddToUsers(user);
5 context.SaveChanges();
6 }
The problem I had here was the "Company" object was from another context (made in the companycontroller), so I thought, I'd just detach the Company object in CompanyController before I return it, so the "AddToUsers()" attaches it again.
Is there a way to make this "AddToUsers" attach this? I can solve my problem by using this code:
1 Company c = new Companycontroller().getCompany(userDTO.Company.companyId);
2 context.AttachTo("Companies", c);
3 user.Company = c;
But I'd prefer a way it's done automatically, because I have a lot more objects and having to hardcode all these attachments will give a lot of messy code..