score:0

I don't know if you've already figured this out, but merging DataContexts is not a good idea. A big part of the reason has to do with the change tracking that is built into the DataContext object. If you were able to keep the entity objects separate so that the changes only affect one DataContext at a time with no overlap, you could get it to work, but it just seems like so much trouble for so little payoff.

You could implement a repository pattern, but again, you still have the problem with one DataContext not recognizing objects created with another DataContext. The project that I am currently working uses only one DataContext. The database has about 75 tables now...I've got one-to-ones, one-to-manys, and many-to-many relationships and I have yet to run into serious performance or implementation issues using only a single DataContext. Using a facade pattern may work, but again, you need to ask yourself if maintaining multiple DataContexts that cannot directly interact is worth the effort.

For example, let's say that you have a Customer table and Orders table. The Customer table resides in one DataContext and the Orders table resides in the other. The relationship is one Customer to zero to many orders. Because you have them in separate DataContexts, I don't believe you can directly refer to the child entity object in your query. So, to get the orders for a particular customer, you may be forced to do this:

var orders = DC2.Orders.Where(a => a.Customer_ID == (DC1.Customers.Where(a => a.Customer_ID == 7).Customer_ID);

instead of this:

var orders = DC.Customers.Where(a => a.Customer_ID == 7).Select(a => a.Orders);

score:0

We achieved this by using inheritance within DataContexts, we use EF5, Code-First and MVC4 for the fron-end web projects.

We have a common DataContext to encapsulate all the common tables in our database

public partial class CommonDataContext : DbContext
{
    //Your code
}

And multiple specialized data contexts that use their own tables + the common tables

public partial class Application1Context : CommonDataContext
{
    //Your code
}

Each one of these data contexts are in separate projects, inside the same solution. Hope this help.

score:1

I'm not aware of anyway to achieve this progmatically.

What you might want to look at is using design-patterns to achieve this goal. By using patterns along with say a repository pattern then you can define your base interface repository that all of the client repositorys will inherit from. Then for each client repository you extend that with their specific needs.

score:2

I would use a Facade Pattern. Create a Facade Context which would abstract the underlying DataContext from the user. You could inherit from Default DataContext if you want and override the methods. Within the overrides, you could pass it to the appropriate DataContext.


Related Query

More Query from same tag