views:

47

answers:

2

The Entity Framework 4 is driving me mad, This situation is:

Employee entity - many to many association - Department entity

I get employees from the EmployeeRepository and Departments from the DepartmentRepository. Each repository uses its own data context. My UI has a list of departments (from the DepartmentRepository) to select for an employee.

When a Department is selected for an Employee, it binds a Department from the DepartmentRepository data context, so when I try to save an Employee it complains with a nifty exception.

I need to keep the data context for Departments separate from the data context for Employees because Departments can be modified and calling save changes on DepartmentRepository cannot also save the Employee.

The separate data contexts works perfectly for my many to 0 or 1 association because I can just bind the Foreign Key property and not the entity instance.

The only workaround I can think of is to fix up the collection in the association by creating another DepartmentRepository with the same data context as the EmployeeRepository, and resolving the DepartmentRepository departments with the departments pulled from the DepartmentRepository with the EmployeeRepository datacontext, but this is just an awful, smelly design and an unacceptable "solution".

At this point I don't care about the code generation strategy (although POCO's would be nice), I really just need something that is going to work, and the Entity Framework 4 isn't terrible at creating the model definitions so I would like to stick with it.

A: 

Check Detach and Attach methods on context. You can Detach entity from one context and Attach it to another. But in that case you lose change tracking and you will have to manually set the state of the entity by context.ObjectStateManager.ChangeObjectState.

But you should really think about design of your application. In mentioned scenario you should not use two different object contexts.

Ladislav Mrnka
A: 

The root cause of your problem is your requirement to separate the data contexts between your two repositories. In order to manage a many-to-many relationship, EF relies on everything being in one object context.

If you really need to enforce a separation between these two contexts, you could model the many-to-many relationship explicitly, i.e. with an intermediate object as two many-to-one relations:

Department - DepartmentEmployee - Employee

The DepartmentEmployee object is 'known' in both contexts. Through the DepartmentRepository you can add/remove employees (via their Id only) and vice versa. There should be no navigation properties from DepartmentEmployee to Department nor Employee.

jeroenh