Base solution for your next web application
Open Closed

How to use second dbcontext in boilerplate? #2346


User avatar
0
paladyr created

I created two AbpDbContext classes but I don't know how to tell my repository to use the second DbContext. I looked at the MultipleDbContextDemoDataModule project but I still don't understand how it knows to use the MySecondDbContext for Courses. The repository I want to use the second DbContext is currently pulling in the first (default) one. Thanks!


3 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    If this entity exists only in one dbContext, then you don't need to do anything. If it exists in more than one dbcontext, you need to create another interface like IRepository and configure it in your second dbContext.

    This is an example of it <a class="postlink" href="https://github.com/aspnetboilerplate/sample-blog-module/blob/master/src/Abp.Samples.Blog.EntityFramework/SampleBlogDbContext.cs">https://github.com/aspnetboilerplate/sa ... Context.cs</a>.

    You can also check sample-blog-module example <a class="postlink" href="https://github.com/aspnetboilerplate/sample-blog-module">https://github.com/aspnetboilerplate/sample-blog-module</a>.

  • User Avatar
    0
    paladyr created

    Sorry for the multiple posts, since I didn't see my first post show up I thought it didn't work but then discovered that my first post has to be approved before it shows up!

    Anyway while I was waiting for my post to be approved I got it working and I'm not sure why it made it work. So previously I defined my AbpDbContext with these constructors:

    public MyDbContext() : base("connString")

    public MyDbContext(DbConnction existingConnection) : base(existingConnection, false)

    public MyDbContext(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection)

    When it was setup like that, my repository was using the default connection string in the default DbContext instead of connString in MyDbContext. As soon as I removed the last two constructors, my repository started using the right connection string (connString) and not the default one. Does that make sense why that was happening? Maybe the 2nd and 3rd constructors force this DbContext to use an existing connection instead of the connection I'm telling it to use?

    Thanks for the rseponse!

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    You are right, if you see the second dbContext here <a class="postlink" href="https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/MultipleDbContextDemo/MultipleDbContextDemo.EntityFramework/EntityFramework/MySecondDbContext.cs">https://github.com/aspnetboilerplate/as ... Context.cs</a> it is defined similar to your final solution.