Multiple contexts with Entity Framework 6, reference entities across dbcontexts

c# entity-framework-6

Question

I am writing two MVC5 (with EF6 and code-first) web apps using generic UnitOfWork that gets the dbContext injected by Unity.

We are required to have two databases (Main Database and Project Specific DB) and have a reference between the two.

Here's an example:

  • in the main context I have an entity Employee
  • in the project context I have an entity Department

I need to create Departments in my Project that group and organize Employees from Main.

Can I have...

ICollection<Employee> Employees { get; set; } in the Project DB's Department Entity ? (the relationship between Employees and Departments is many-to-many)

How would you go about having something like this done ?

1
1
3/20/2014 1:37:41 PM

Accepted Answer

The easiest approach would be to link tables from one database to the other so that this is the database server which handles two physical databases as one virtual database.

Then, in EF, you have just one context with tables from both databases and querying/joins etc. works correctly.

http://msdn.microsoft.com/en-us/library/ff772782.aspx

Otherwise, linking two databases in the application layer with EF and two contexts sounds impossible.

2
3/20/2014 2:29:55 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow