EntityFramework context across multiple projects or joining between two contexts

c# entity-framework entity-framework-core


I have a class library project containing an EF Core db context. This is part of a framework.

I want to extend this context but without making changes to the framework project. The second context would use the same database.

I created another db context in a different class library (something similar to this). This works ok, I can make queries and create migrations separately from the other context.

But for example if I have a User entity in the first context and UserBooks in the second, when I try to make a join between the two contexts it doesn't work, getting exception

System.ArgumentNullException: Value cannot be null. Parameter name: entityType

This is a known issue.

Also tried with latest NuGet package 3.0.0-preview3.19153.1 but the only difference is that the error message is better

Cannot use multiple DbContext instances within a single query execution. Ensure the query uses a single context instance

Is there any way to

a. make joins between two contexts


b. extend a context in a separate project without making any (or minimal) changes to the 'main' context

3/29/2019 7:07:04 AM

Popular Answer

You could make your second context inherit the first.

public class MyFirstContext : DbContext
    public DbSet<User> Users { get; set; }

public class MySecondContext : MyFirstContext
    public DbSet<UserBook> UserBooks { get; set; }

Of course, your second context could be in a different assembly. Now you only need MySecondContext in your application. You will be able to join Users and UserBooks.

3/29/2019 7:23:20 AM

Related Questions


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