If you see ‘An entity object cannot be referenced by multiple instances of IEntityChangeTracker‘ exception its likely you have created two entity framework db contexts and are tracking a particular entity from both of them when calling savechanges(). Although there may be some cases for wanting two db contexts this is likely not want you want. Two main approaches to solving this and ensuring your dealing with the one context..
Explicitly passing the same context into each of your service or repository classes. Rather than creating a new DB context in each of your service classes create the context at a higher level (perhaps in controller/base controller) and just pass it into your worker classes…
ContextDB _db = new ContextDB();
OrderService orderService = new OrderService(_db);
CustomerService customerService = new CustomerService(_db);
Using an IOC container such as Ninject to manage the lifetime of the context class for you. Per-Request is recommended for web applications which means a single db context will be shared across the whole of a single request. Ninject is simple enough to configure, a per request binding looks similar to below…