简体   繁体   中英

Can you create a sub DbContext from another DbContext in EntityFramework Core?

Say I have an existing DbContext, is there a way to create another DbContext that uses that DbContext?

Basically, I'm interested in exposing different DbContext's to different applications, but want them to all work from the originating DbContext.

This could be used for versioning, security, and more.

I can create different DTOs, but then I lose a lot of the power of IQueryable.

I am not sure if I understand right but you register another db context like this with the same app (supposedly different database)

services.AddDbContext<ApplicationDbContext2>(
    options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));

and you define it as you defined #1.

the part worries me is:

I'm interested in exposing different DbContext's to different applications, but want them to all work from the originating DbContext

Dbcontext in defined within your application to keep track of the state of your application. If the state of application is depended on other applications you are talking about microservices and you need to use other tools to tell to your app to update its own state. For example you can call an endpoint (ideally via gRPC) or use event busses.

We used to share databases between apps (and some still do) but that is not a very good idea as changes in database for one app may cause bugs on other dependent apps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM