Using Multiple EF Core DbContexts in a Single Application

Поделиться
HTML-код
  • Опубликовано: 23 ноя 2024

Комментарии • 161

  • @MilanJovanovicTech
    @MilanJovanovicTech  Год назад +3

    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

    • @GGGStalker
      @GGGStalker Год назад

      Can I ask for a discount on ur course I’m divorced and don’t have to much on spending account please help

  • @alexmadnix
    @alexmadnix Год назад +4

    I have already used multiple Ef cores, but your lecture is beneficial for me to watch again.

  • @baranacikgoz
    @baranacikgoz Год назад +1

    I was coding the base for a modular monolith project, and I saw the notification. Just happiness.

  • @GlebWritesCode
    @GlebWritesCode Год назад +3

    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

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад

      Something similar to DB per tenant

    • @pejterr1
      @pejterr1 9 дней назад

      Hello
      Have the same issue,
      How to approach this topic to register in service collection multiple databases using single DBcontext class?
      Already tried AddKeyedSingleton but later have issue with shearing this between thread/api requests...

    • @GlebWritesCode
      @GlebWritesCode 9 дней назад +1

      @@pejterr1 we used different classes for those cases, if I remember correctly. One for writes and one for reads

  • @pcostarg
    @pcostarg Год назад +3

    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!

  • @RobertGaudyn
    @RobertGaudyn Год назад +3

    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).

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад

      So you're actually using the context manager, and it know which DbContext to use?

    • @RobertGaudyn
      @RobertGaudyn Год назад

      @@MilanJovanovicTech yes. That was a goal of this approach

    • @000ahamed
      @000ahamed 9 месяцев назад

      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?

  • @piotrkowalski3460
    @piotrkowalski3460 Год назад +2

    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.

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад

      Why not combine EF to create scripts with DbUp to execute them?

  • @rustamhajiyev
    @rustamhajiyev Год назад +5

    Really good one, thanks a lot :) these tips will definitely safe many devs from figuring things out the hard way

  • @dawidbiell
    @dawidbiell Год назад +1

    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

  • @remyjoseacostamelo
    @remyjoseacostamelo Год назад +2

    Oh man, excellent! thanks a lot. 🙏🏾
    Can't wait for you to do a video on multitenancy.

  • @NagadGames
    @NagadGames Год назад +1

    🎉 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

  • @yasirmehmood9247
    @yasirmehmood9247 Год назад +1

    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?

  • @andyhb1970
    @andyhb1970 7 месяцев назад

    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.

  • @infotips2475
    @infotips2475 11 месяцев назад +1

    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!

    • @MilanJovanovicTech
      @MilanJovanovicTech  11 месяцев назад +1

      The second argument of that method is a Func which you can use to filter the types :)

  • @disglaceful39
    @disglaceful39 Год назад +1

    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?

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад

      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...

  • @borisgomiunik7960
    @borisgomiunik7960 Год назад +1

    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)?

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад +1

      Nope, you can't use joins between different DbContexts
      You can first query the Products, and then store that info (duplicated) in the Order

  • @zokocx
    @zokocx Год назад +1

    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.

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад

      I didn't want to make it too long, but great point!

    • @UndersVzLOM
      @UndersVzLOM Год назад

      @@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

  •  Год назад +1

    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.

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад +1

      Ah, that's a tough one! I'll see how to make that into a video.

  • @michaelsteffen7220
    @michaelsteffen7220 Год назад +1

    I really like the Visual Studio dark theme you are using. Would you share which one it is?

  • @oguzhancengiz1875
    @oguzhancengiz1875 2 месяца назад

    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?

  • @liip3lima
    @liip3lima 9 месяцев назад

    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?

    • @MilanJovanovicTech
      @MilanJovanovicTech  9 месяцев назад

      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

  • @volodymyrliashenko1024
    @volodymyrliashenko1024 Год назад +2

    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.

  • @stevenholland4771
    @stevenholland4771 14 дней назад

    I'm curious what your solution would be for a similar but different usage. Say you want to have the code for an API only, say different modules, but you want to combine them as needed so that you COULD handle joins for common entities between API sets. Say you have 3 modules, users management, blogs, and inventory management. I want to mix and match modules on a per project basis. So user management would be used by both blogs and inventory management. Like you could write separate projects for each that has the entities and set of relevant APIs, but then when you want to use them in a front-end or web api project you somehow combine then into a single context (in a streamlined way besides manually constructing the unique context for each project). Like if there was some way to provide a default context in each module (which I would would be necessary to write any APIs for those entities) but have it all combine in the deployable project depending on what modules you choose. Do you get me? What do you think?

    • @MilanJovanovicTech
      @MilanJovanovicTech  13 дней назад

      Sounds like something you can solve with object composition

  • @cleitoncarlospereira2006
    @cleitoncarlospereira2006 9 месяцев назад +1

    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.

    • @MilanJovanovicTech
      @MilanJovanovicTech  9 месяцев назад

      And we would asynchronously create this replica?

    • @cleitoncarlospereira2006
      @cleitoncarlospereira2006 9 месяцев назад

      @@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.

  • @MohiyoDeen
    @MohiyoDeen Год назад +1

    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 ?

  • @mohammadkalbouneh7892
    @mohammadkalbouneh7892 8 месяцев назад +1

    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

  • @ahmedh2482
    @ahmedh2482 Год назад +1

    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?

  • @microtech2448
    @microtech2448 Год назад +1

    Thanks for sharing the information. One thing, what's your opinion on using DBUp vs EF Core Migration?

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад

      How about EF Core for generating migrations (SQL scripts) and DbUp for running them?

    • @microtech2448
      @microtech2448 Год назад

      @@MilanJovanovicTech that would be interesting to see if you have anything ready around it.

  • @lukaskuchta1010
    @lukaskuchta1010 Год назад +1

    Hi Milan. can you cover in the futere video LoggerMessage pattern ?

  • @carmineos
    @carmineos Год назад +1

    What about using TransactionScope and enlist the single transactions from each DbContext?

  • @mohammedessaddek8175
    @mohammedessaddek8175 Год назад +1

    Hello, do you have any idea about how to manage domain events across those multiple contexts?

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад

      You don't, they're kept separate

    • @mohammedessaddek8175
      @mohammedessaddek8175 Год назад

      @@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 ?

  • @unskeptable
    @unskeptable Год назад +1

    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 ?

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад +1

      You should definitely handle disposing each time

    • @unskeptable
      @unskeptable Год назад

      Isn't the dbContext automatically disposed when the request ends ?

  • @FabioGalanteMans
    @FabioGalanteMans Год назад +1

    Milan, how are you?
    Are you using Git Copilot?

  • @_iPilot
    @_iPilot Год назад +2

    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.

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад

      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.

    • @_iPilot
      @_iPilot Год назад

      @@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.

  • @GGGStalker
    @GGGStalker Год назад +1

    What about micro services architecture when it’s required to use different db for each service?

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад

      Different DB - different DbContext. Should work like a charm.

  • @Tim61400
    @Tim61400 Год назад

    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 😎

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад +1

      Yes, logical separation in your code is good use case. But writing cross-context queries will be problematic for sure.

  • @kodindoyannick5328
    @kodindoyannick5328 8 месяцев назад +1

    Awesome content! Thanks Milan

    • @MilanJovanovicTech
      @MilanJovanovicTech  8 месяцев назад

      Sure thing! I'm planning a V2 of this video with Hangfire

  • @mbradea
    @mbradea Год назад +1

    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.

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад

      That's a great suggestion, and will certainly require a more in-depth video to answer!

    •  Год назад +1

      @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.

  • @svorskemattias
    @svorskemattias Год назад +1

    I use 6 dbcontexts. 3 bounded contexts with one read and one write dbcontext each

  • @anatolygalaxy9218
    @anatolygalaxy9218 11 месяцев назад

    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 )

    • @MilanJovanovicTech
      @MilanJovanovicTech  11 месяцев назад

      Yes, you can exclude an entity from Migrations for a particular DbContext

  • @thabangmaleswena5846
    @thabangmaleswena5846 4 месяца назад

    i got the dbcontext in different libraries. do i have to do the map in the api for all my queries?

  • @MahmoudSaed98
    @MahmoudSaed98 Год назад +1

    When I have more than one layer in the project
    How do I perform the migration process?

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад +1

      The same? Just target the proper project

    • @MahmoudSaed98
      @MahmoudSaed98 Год назад

      Do you have a video explaining this? @@MilanJovanovicTech

  • @gooalastor
    @gooalastor Год назад +1

    Awesome, as always!

  • @psybuck2002us
    @psybuck2002us Год назад +1

    How could you apply multiple DbCOntexts for a multi tenant application with per tenant database?

  • @kurtnelle
    @kurtnelle Год назад +2

    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.

  • @lukaskuchta1010
    @lukaskuchta1010 Год назад +1

    How to implement Uow pattern for this approach?

  • @vivekkaushik9508
    @vivekkaushik9508 Год назад +1

    What's the use case of using multiple dbcontext instead of one?

  • @sunzhang-d9v
    @sunzhang-d9v Год назад

    Different databases, different contexts can be associated with queries?

  • @eddypartey1075
    @eddypartey1075 Год назад +1

    Is it ok to separate domain dbcontext and identity dbcontext?

  • @mrchali-rl8es
    @mrchali-rl8es Год назад +2

    can we use different database such as oracle and sql

    • @gooalastor
      @gooalastor Год назад +1

      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.

    • @DjDanny32
      @DjDanny32 Год назад

      Absolutely. They are completely different connections, so they could be on different planets if you want!

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад

      Yeah, you definitely can. And this would be one of the reasons you'd want to do this in the first place.

  • @Hallo503
    @Hallo503 Год назад +1

    is it possible to use multiple dbContext objects to concurrently read the database?

    • @Hallo503
      @Hallo503 Год назад

      @@dmitrymezinov9238 so it is possible, but I have to explicitly create a new dbContext for every thread?.

    • @dmitrymezinov9238
      @dmitrymezinov9238 Год назад

      @@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.

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад +1

      As long as it's a different DbContext instance it should work

  • @PROFDAILY
    @PROFDAILY Год назад +1

    very helpful

  • @susantamaji2941
    @susantamaji2941 6 месяцев назад

    Thank you milan. Very nice.

  • @vladimirv.443
    @vladimirv.443 2 месяца назад

    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

    • @MilanJovanovicTech
      @MilanJovanovicTech  2 месяца назад

      Why not just switch the connection string?

    • @vladimirv.443
      @vladimirv.443 2 месяца назад

      @@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?

  • @imanqoly
    @imanqoly 4 месяца назад

    I did multiple dbcontext simply becasue I had to separate my identities and items(products and services) also a read-only context.

  • @manishb7703
    @manishb7703 6 месяцев назад

    Can you do a video on IULD identifier and how you can use it with dot net 8

    • @MilanJovanovicTech
      @MilanJovanovicTech  6 месяцев назад

      Been planning to for a while, but never got around to do it 😁

    • @manishb7703
      @manishb7703 6 месяцев назад

      @@MilanJovanovicTech thank you Milan for all the hardwork you put in. Do you mind sharing some pointers on this topic.

  • @sunzhang-d9v
    @sunzhang-d9v Год назад

    Can different database instances and different contexts be associated with queries?

  • @pathummadhusanka4698
    @pathummadhusanka4698 Год назад +1

    How can we set value object as ID in EF core?

    • @michaldivismusic
      @michaldivismusic Год назад +1

      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.

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад +1

      Define a value conversion, or check out Complex types in EF 8

  • @ulvidemirsoy2558
    @ulvidemirsoy2558 4 месяца назад

    Great video

  • @techpc5453
    @techpc5453 Год назад +1

  • @bjmmedeiros13
    @bjmmedeiros13 Год назад +1

    The word "database" has lost all its meaning to me after this video lol
    Database? Database

    • @MilanJovanovicTech
      @MilanJovanovicTech  Год назад +1

      Why?

    • @bjmmedeiros13
      @bjmmedeiros13 Год назад

      @@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?

    • @bjmmedeiros13
      @bjmmedeiros13 Год назад

      @@MilanJovanovicTech btw, I'm new to the channel but you seem to produce high quality content Milan!
      Keep up with the good work