Get the source code for this video for FREE → the-dotnet-weekly.ck.page/multiple-dbcontexts Want to master Clean Architecture? Go here: bit.ly/3PupkOJ Want to unlock Modular Monoliths? Go here: bit.ly/3SXlzSt
@GGGStalker11 ай бұрын
Can I ask for a discount on ur course I’m divorced and don’t have to much on spending account please help
@alexmadnix11 ай бұрын
I have already used multiple Ef cores, but your lecture is beneficial for me to watch again.
@MilanJovanovicTech11 ай бұрын
Awesome, glad it was helpful :)
@rustamhajiyev11 ай бұрын
Really good one, thanks a lot :) these tips will definitely safe many devs from figuring things out the hard way
@MilanJovanovicTech11 ай бұрын
Hope so!
@baranacikgoz11 ай бұрын
I was coding the base for a modular monolith project, and I saw the notification. Just happiness.
@MilanJovanovicTech11 ай бұрын
Sweet 😁
@pcostarg11 ай бұрын
I would like to see a deep dive into migrations. Specially changes to a production database and how that would work with changes to the schema of a database. Thanks for all the Awesome videos!
@MilanJovanovicTech11 ай бұрын
Great suggestion!
@remyjoseacostamelo11 ай бұрын
Oh man, excellent! thanks a lot. 🙏🏾 Can't wait for you to do a video on multitenancy.
@MilanJovanovicTech11 ай бұрын
Coming soon!
@remyjoseacostamelo11 ай бұрын
@@MilanJovanovicTech
@RobertGaudyn11 ай бұрын
My team uses two database contexts. One of the connection strings is configured with the ApplicationIntent=ReadOnly flag. Above these contexts, we have a context manager and it decides which context is to be used depending on the purpose (writing/reading). Both contexts addresses same listener, but connects to different servers: primary (write) and secondary (read).
@MilanJovanovicTech11 ай бұрын
So you're actually using the context manager, and it know which DbContext to use?
@RobertGaudyn11 ай бұрын
@@MilanJovanovicTech yes. That was a goal of this approach
@000ahamed7 ай бұрын
how does the context manager knows that which db context to use ? do u pass something like a parameter in for every db context initialization mentioning whether its a read/write?
@dawidbiell11 ай бұрын
Greate video! I am junior software dev and this question came to my mind few weeks ago. Cool explenation and clarify example. Just in time to get rid of my concerns :) Thx
@MilanJovanovicTech11 ай бұрын
Glad it was helpful!
@piotrkowalski346011 ай бұрын
When using multiple db contexts I recommend using external tools for database migrations like FluentMigrator or DbUp. It's really easy to get lost in EF migrations. Before you notice you spend most of your time fighting with your models to generate the right migration's code. Also it's troublesome to migrate all the db contexts before deploying applications in your release pipeline.
@MilanJovanovicTech11 ай бұрын
Why not combine EF to create scripts with DbUp to execute them?
@GlebWritesCode10 ай бұрын
I have another use-case - create multiple instances of same DbContext (that use different connection strings) to query different shards of your data (meaning each shard is a separate database) in parallel
@MilanJovanovicTech10 ай бұрын
Something similar to DB per tenant
@NagadGames11 ай бұрын
🎉 Excellent, I'd like If you can give It a little zoom in on those tiny letters that are hard to read from our side, maybe increasing the environment font size
@MilanJovanovicTech11 ай бұрын
Which letters specifically?
@gooalastor11 ай бұрын
Awesome, as always!
@MilanJovanovicTech11 ай бұрын
Thank you! Cheers!
@kodindoyannick53286 ай бұрын
Awesome content! Thanks Milan
@MilanJovanovicTech6 ай бұрын
Sure thing! I'm planning a V2 of this video with Hangfire
11 ай бұрын
Hi Milan. Great videos as always! Thanks for your hardwork and high quality videos. Wondering if you can create a video showing your recommendation to avoid downtimes (or minimize it) when deploying changes in the DB schema with Entity Framework. Thanks in advance.
@MilanJovanovicTech11 ай бұрын
Ah, that's a tough one! I'll see how to make that into a video.
@cleitoncarlospereira20066 ай бұрын
Hello Milan, once again, thank you for the rich content you present on your channel. Could you discuss in a video, what would be the most elegant strategy so that I can create a replica in a NoSql database (MongoDb for example) to serve as a read-only database? I know I could use EF Interceptors, however, it would be interesting to have a generic form without having to specify the model as in the example shown in the Outbox Pattern video.
@MilanJovanovicTech6 ай бұрын
And we would asynchronously create this replica?
@cleitoncarlospereira20066 ай бұрын
@@MilanJovanovicTech It could be asynchronously too, but I believe that doing it synchronously right after the commit in the recording database would help a lot, even though we know that this could impact the system's performance, the problem with doing it asynchronously I believe is that would be the guarantee that the data was written to the read database.
@zokocx11 ай бұрын
Useful content. I nice stuff at the end about drawnbacks and how to use transaction but also you didn't mention that you can use connection from one DbContext in transaction or you can control connection to explicitly through some connection factory.
@MilanJovanovicTech11 ай бұрын
I didn't want to make it too long, but great point!
@UndersVzLOM11 ай бұрын
@@MilanJovanovicTech thank you for video, can we please have extra video on how to correctly make transactions. As already mentioned there's tech possibility to use common connection but how to configure scopes properly, how to inject connections, how to manage services etc. Thank you
@PROFDAILY11 ай бұрын
very helpful
@MilanJovanovicTech11 ай бұрын
Glad you think so!
@disglaceful3911 ай бұрын
Great tutorial Milan, I love following your videos. I'm curious, in the case of a modular monolith, the creation of an order would occur in the Orders module which would not have access to the ProductsDbContext. In that instance, how would you access the products needed to create an order? Would the Order module query the Products module using a service abstracted using an interface?
@MilanJovanovicTech11 ай бұрын
In case of a Modular monolith, you would only care about a Product ID from the Order module (plus some pricing info probably). In that case, you will grab the data at runtime using the public API of the products module - as you suggested. Another solution is to store a local copy of the data, but then you need to maintain that...
@_iPilot11 ай бұрын
Why not just initially place contexts in different assemblies? Each of them will have own default migrations folder and no -DbContext argument will be required - it will be detected by chosen assembly.
@MilanJovanovicTech11 ай бұрын
I think this example was helpful in terms of understanding the limitation and the CLI. But yeah, in most cases they would live in different assemblies.
@_iPilot11 ай бұрын
@@MilanJovanovicTech Personally, I do not appreciate partial examples, especially those that contain practices that are considered bad. Placing contexts into separate assemblies is not a big deal and it also gives an opportunity to show how to manage such contexts using visual studio and to make a comparison between approaches in one video.
@michaelsteffen722011 ай бұрын
I really like the Visual Studio dark theme you are using. Would you share which one it is?
@MilanJovanovicTech11 ай бұрын
It's native dark theme + ReSharper syntax highlighting
@michaelsteffen722011 ай бұрын
Thank you@@MilanJovanovicTech
@mohammadkalbouneh78926 ай бұрын
I'm trying to build a clean architecture for all of my projects in one solution and since the databases already has data so I'm trying to scaffold the databases first and i have multiple db context because of that still i can't make it to a full working project wish you make a video on scaffolding, multiple schemas, database first, clean architecture
@MilanJovanovicTech6 ай бұрын
That could be a good idea
@yasirmehmood924711 ай бұрын
Hi Milan, Great Video. I have a question. you did not establish navigation prosperity within LineItems and Product Entities. So how to get Order details with the name of the Product in that order?
@MilanJovanovicTech11 ай бұрын
Different DbContexts - can't do that.
@infotips24759 ай бұрын
I have two contexts in the same assembly, and I also have separate Fluent API configurations in different folders. In the OnModelCreating method, I have to manually ignore the entities from the other context. How can I specify configurations based on the folder path and not the assembly? How should this be handled? Thank you!
@MilanJovanovicTech9 ай бұрын
The second argument of that method is a Func which you can use to filter the types :)
@liip3lima7 ай бұрын
Excellent content! One question that remained and I couldn't find anything specific on the internet, making it necessary to relate tables with different contexts, what would it look like? For example: I created a context to deal with all tables related to user inputs and a context to deal with all system calculation tables, but a relationship is made within the DbContext (in the scenario of a single DbContext) to say that input table A is a foreign key in calculation table B. What would it look like in the case of two DbContext?
@MilanJovanovicTech7 ай бұрын
I don't think it's doable, and I'm certain it's not suggested to do it that way. You can probably create the FK references at the database level. In general, it's not recommended to mix these DbContexts at runtime
@susantamaji29414 ай бұрын
Thank you milan. Very nice.
@MilanJovanovicTech4 ай бұрын
Thank you too!
@volodymyrliashenko102411 ай бұрын
I'm using one dbcontext and DB for parallel queries. I have custom DbFactory to make sure every parallel query has its own DB Context instance.
@mediaatul11 ай бұрын
Do you mind sharing code, will see if could use some idea
@volodymyrliashenko102411 ай бұрын
@@mediaatul not for sharing but for parallel SQL queries with EF core.
@MilanJovanovicTech11 ай бұрын
Interesting!
@user-xm7sh3vw8o11 ай бұрын
It doesn't make a lot of sense, I've had it
@volodymyrliashenko102411 ай бұрын
@@user-xm7sh3vw8o SQL parallel requests doesn't make sense?
@Tim614009 ай бұрын
Would that be ok to use multiple dbcontext in a single application just to separate small semantic part of the database. For example: all that is related to users is in one dbcontext, everything related to products/orders/etc. In another one used and this kind of goes for all "main features". I guess this goes into the Modular Monolith? Asking because we have a database over 200-300 tables and it sounds a bit overwhelming to have one dbcontext for everything.. What do you think? My only concern is about performance of having to write multiple queries for features that covers multiple semantic contexts (i.e. multiple db contexts)... Not sure if that's clear enough... ? Any way, thanks for your very helpful videos and for being awesome 😎
@MilanJovanovicTech9 ай бұрын
Yes, logical separation in your code is good use case. But writing cross-context queries will be problematic for sure.
@borisgomiunik796011 ай бұрын
Nice explanation, thanks. I have it set up very similar. Is there any particular way of joining data from two datacontexts (e.g. showing product names in the order)?
@MilanJovanovicTech11 ай бұрын
Nope, you can't use joins between different DbContexts You can first query the Products, and then store that info (duplicated) in the Order
@andyhb19705 ай бұрын
Hi Milan, what are your thoughts on common entities between db contexts, specifically when you have a complete DDD structured app using the repository pattern and IUnitOfWork? I am wanting to create a database per application type in my solution and then have a set of common tables that are always present in all application databases e.g. tblOutboxMessages, tblEmailHistory etc.
@MilanJovanovicTech5 ай бұрын
Yeah, I reuse that across contexts
@carmineos11 ай бұрын
What about using TransactionScope and enlist the single transactions from each DbContext?
@MilanJovanovicTech11 ай бұрын
No idea how that will behave when using different DBs 🤔
@mrchali-rl8es11 ай бұрын
can we use different database such as oracle and sql
@gooalastor11 ай бұрын
It should be OK from what I saw. It's just that you should use oracle to ef lib, like in the beginning of video.
@DjDanny3211 ай бұрын
Absolutely. They are completely different connections, so they could be on different planets if you want!
@MilanJovanovicTech11 ай бұрын
Yeah, you definitely can. And this would be one of the reasons you'd want to do this in the first place.
@oguzhancengiz187515 күн бұрын
Hello, I have 2 contexts and both have memory tables, one is the archive db. I need to retrieve records from the archive db for queries exceeding 3 months, and since there is pagination, I need an IQueryable query. Do you have any suggestions?
@MilanJovanovicTech14 күн бұрын
Not really
@microtech244811 ай бұрын
Thanks for sharing the information. One thing, what's your opinion on using DBUp vs EF Core Migration?
@MilanJovanovicTech11 ай бұрын
How about EF Core for generating migrations (SQL scripts) and DbUp for running them?
@microtech244811 ай бұрын
@@MilanJovanovicTech that would be interesting to see if you have anything ready around it.
@GGGStalker11 ай бұрын
What about micro services architecture when it’s required to use different db for each service?
@MilanJovanovicTech11 ай бұрын
Different DB - different DbContext. Should work like a charm.
@ahmedh248211 ай бұрын
I planning to use two dbContext in my winform app one to deal with sql service and the other deal with local sqlite, what do you think about that?
@MilanJovanovicTech11 ай бұрын
Smart idea
@mohammedessaddek817511 ай бұрын
Hello, do you have any idea about how to manage domain events across those multiple contexts?
@MilanJovanovicTech11 ай бұрын
You don't, they're kept separate
@mohammedessaddek817511 ай бұрын
@@MilanJovanovicTech okey, so how to handle this use case if we need to communication in this case ? In my case I have two contexts, one for identity (not aggregate root) and one with only aggregate roots ?
@MahmoudSaed9810 ай бұрын
When I have more than one layer in the project How do I perform the migration process?
@MilanJovanovicTech10 ай бұрын
The same? Just target the proper project
@MahmoudSaed9810 ай бұрын
Do you have a video explaining this? @@MilanJovanovicTech
@MohiyoDeen11 ай бұрын
What if I want to use Separate Db per request. Like getting TenantID from Header with each HTTP Request to generate Connection String and then DbContext ?
@MilanJovanovicTech11 ай бұрын
Then just manually create the context or use a factory
@kurtnelle11 ай бұрын
Long story short, if the contexts target the same DB instance, make sure they use different DB schema names or the migration histories table will get messed up. Got it.
@MilanJovanovicTech11 ай бұрын
✅
@FabioGalanteMans11 ай бұрын
Milan, how are you? Are you using Git Copilot?
@MilanJovanovicTech11 ай бұрын
Doing great, and you? I'm not using Copilot
@FabioGalanteMans11 ай бұрын
@@MilanJovanovicTech why when you typing the VS autocomplet the code?
@MilanJovanovicTech11 ай бұрын
@@FabioGalanteMans ReSharper
@unskeptable11 ай бұрын
If using DbContext without DI can you do new DbContext() on top of controller and use it in Actions or do you need to do using(var db= new DbContext) to handle Disposing each time ?
@MilanJovanovicTech11 ай бұрын
You should definitely handle disposing each time
@unskeptable11 ай бұрын
Isn't the dbContext automatically disposed when the request ends ?
@psybuck2002us11 ай бұрын
How could you apply multiple DbCOntexts for a multi tenant application with per tenant database?
@MilanJovanovicTech11 ай бұрын
I need to do a multi-tenancy video ASAP
@lukaskuchta101011 ай бұрын
How to implement Uow pattern for this approach?
@MilanJovanovicTech11 ай бұрын
You don't - each context is a separate UoW
@lukaskuchta101011 ай бұрын
Hi Milan. can you cover in the futere video LoggerMessage pattern ?
@MilanJovanovicTech11 ай бұрын
Maybe, good suggestion
@mbradea11 ай бұрын
Thanks for covering the scenario where the entities in each context are completely different and they have no overlaps or joins between them. However in real-world circumstances this seldom is the chance, and you have different sub-domains that need to share the same logical entities (ie: tables and IDs), and I’d love to know how this would be dealt with via multiple contexts. For example in your example orders need to reference products, so even if you have two different “catalogue” and “orders” domains, these should NOT reference different tables with a separate schema, as this duplicates information, creates multiple versions of the truth, and overall throws out the entire “relational” benefits of a database out the window. Same thing happens with any data that is linked to a user. Sub-systems in domains are generally hierarchical in nature, so Users/Accounts might be managed by one system/module, but multiple other sub-systems/modules need to refer their entities to these user tables. Would love it if you could dive into these “overlapping entities” scenario - perhaps in another video - as basically any system I’ve built ever always had this notion of sub-domains needing to link/refer to domain agregate root entities within another, even when you are disciplined and split out the dependencies so there are no cycles (ie: hierarchical sub-domains) and keep strict access to sub-entities through aggregate roots.
@MilanJovanovicTech11 ай бұрын
That's a great suggestion, and will certainly require a more in-depth video to answer!
11 ай бұрын
@mbradea visualize a microservice architecture. To avoid creating dependencies between them and making synchronous calls, the owner of the data should push the information to the consumer. The consumer then saves a copy of the data, and uses that. So yes, ideally they should be different tables. The source of truth is always the owner of the data, and the consumer has a copy with eventual consistency. It doesn't need to be an exact copy, the consumer can manipulate / transform / aggregate the data to better suit it's need, but they will always be a copy and never a source of truth. In a modular monolith you should follow the same pattern. However, a trick I use often to simulate a copy of this data without spending the time to create this information pushing between boundaries is to create a view that access the required information and map it to a query type in the db context. Being a query type I know my consumer will never change the information, and being a view I can create the necessary transformations to return the data as I want instead of creating a dependency on the original.
@eddypartey107511 ай бұрын
Is it ok to separate domain dbcontext and identity dbcontext?
@MilanJovanovicTech11 ай бұрын
Yes
@vivekkaushik950811 ай бұрын
What's the use case of using multiple dbcontext instead of one?
@MilanJovanovicTech11 ай бұрын
Did you watch the video?
@lettuceturnipthebeets79011 ай бұрын
@@MilanJovanovicTechnice :D
@ulvidemirsoy25582 ай бұрын
Great video
@MilanJovanovicTech2 ай бұрын
Glad you enjoyed it
@thabangmaleswena58462 ай бұрын
i got the dbcontext in different libraries. do i have to do the map in the api for all my queries?
@MilanJovanovicTech2 ай бұрын
Why can't you do it at a lower level?
@svorskemattias11 ай бұрын
I use 6 dbcontexts. 3 bounded contexts with one read and one write dbcontext each
@MilanJovanovicTech11 ай бұрын
That's a rich application :)
@techpc545311 ай бұрын
@MilanJovanovicTech11 ай бұрын
👋👋👋👋
@anatolygalaxy92189 ай бұрын
Hi, great video and good explanation 😊 a pleasure to follow and easy to understand, thanks for sharing I actually have a question, what if you have a table that is shared across both dbContexts? Both are pointing to the same physical database, how to divide migrations in that case? My assumption is that all the migrations will be only under one dbContext, even if the table is shared across both. Thanks in advance )
@MilanJovanovicTech9 ай бұрын
Yes, you can exclude an entity from Migrations for a particular DbContext
@Hallo50311 ай бұрын
is it possible to use multiple dbContext objects to concurrently read the database?
@Hallo50311 ай бұрын
@@dmitrymezinov9238 so it is possible, but I have to explicitly create a new dbContext for every thread?.
@dmitrymezinov923811 ай бұрын
@@Hallo503 It depends on your goal. If your application is multi-threaded and it needs to work with DB from different threads simultaneously, then yes - in each such thread you need to create its own separate DbContext. In other words you cannot share DbContexts between threads. This is due to DbContext is not thread-safe. But if your application is single-threaded, then you can create and use multiple contexts in it, just in one thread. This is what Milan showed in his video. Notice, that in such case there will be no "concurrently reading the database" via several contexts. This will be sequential access through one, then through another context.
@MilanJovanovicTech11 ай бұрын
As long as it's a different DbContext instance it should work
@xxXAsuraXxx11 ай бұрын
Does unit of work work on multiple dbcontext?
@MilanJovanovicTech11 ай бұрын
How would you implement it?
@user-xm7sh3vw8o11 ай бұрын
Different databases, different contexts can be associated with queries?
@MilanJovanovicTech11 ай бұрын
What does that mean?
@pathummadhusanka469811 ай бұрын
How can we set value object as ID in EF core?
@michaldivismusic11 ай бұрын
You need to specify how it will be converted to and from a primitive value in the database using the HasConversion method on the property in OnModelCreating.
@MilanJovanovicTech11 ай бұрын
Define a value conversion, or check out Complex types in EF 8
@vladimirv.44313 күн бұрын
Cool video! 🔥 Could you please tell me how to create several identical DbContexts, but for different databases. Probably an array of DbContext 🙄 The database structure is completely the same, just different SQL servers. (No migration needed) I'd like to have a connection to all databases and get data from some base depending on post parameters
@MilanJovanovicTech13 күн бұрын
Why not just switch the connection string?
@vladimirv.44313 күн бұрын
@@MilanJovanovicTech I need to load data from all databases. I use services.AddDbContext to add one connection. But now I need to do it multiple times, using different connection strings. I could create a new instance DataBaseContext each time, but I don't think that's the good idea?
@user-xm7sh3vw8o11 ай бұрын
Can different database instances and different contexts be associated with queries?
@MilanJovanovicTech11 ай бұрын
What does that mean?
@user-xm7sh3vw8o11 ай бұрын
@@MilanJovanovicTech Two different contexts, can you query jointly?
@manishb77034 ай бұрын
Can you do a video on IULD identifier and how you can use it with dot net 8
@MilanJovanovicTech4 ай бұрын
Been planning to for a while, but never got around to do it 😁
@manishb77034 ай бұрын
@@MilanJovanovicTech thank you Milan for all the hardwork you put in. Do you mind sharing some pointers on this topic.
@imanqoly2 ай бұрын
I did multiple dbcontext simply becasue I had to separate my identities and items(products and services) also a read-only context.
@MilanJovanovicTech2 ай бұрын
That's a common use case 👌
@bjmmedeiros1311 ай бұрын
The word "database" has lost all its meaning to me after this video lol Database? Database
@MilanJovanovicTech11 ай бұрын
Why?
@bjmmedeiros1311 ай бұрын
@@MilanJovanovicTech no big deal, I think it was sort of unavoidable to repeat the word "database" many times in the video 😁 And words tend to lose their meaning when someone says them in rapid succession, right?
@bjmmedeiros1311 ай бұрын
@@MilanJovanovicTech btw, I'm new to the channel but you seem to produce high quality content Milan! Keep up with the good work