skip to Main Content

On Startup.cs, the application establishes connection with the database.

services.AddDbContext<DataContext>(opt=>
  opt.UseSqlLite(_config.GetCinnectionString(‘DefaultConnectionString’));
});

This opt object of the now established database connection is injected as options to the DataContext class-

public class DataContext:DbContext
{
   public DataContext(DbContextOptions options):base(options)
}

And further on, whenever DataContext is referred to on different classes like

public class SomeMethod
{
   private readonly DataContext _context;
   SomeMethod(DataContext context)
   {
     _context = context:
   }
}

The execution flow is –
SomeMethod=>DataContext(which gets its options object from Startup) referring to the applications session with the database.

I hope we are not establishing a new connection with the database each time we are referring to DataContext.

Would love to read the answers. And please feel free to add details/intricacies to the flow as I haven’t been able to find many answers regarding this.

2

Answers


  1. Check here everything for EF Core
    https://www.entityframeworktutorial.net/efcore/entity-framework-core-dbcontext.aspx

    Тhe way a question is asked requires a massive answer.
    Here you can see specific for timeout:
    https://quick-adviser.com/what-is-the-default-timeout-in-entity-framework/

    here you can read everything for the DBContext in Asp.Net
    https://www.tutorialspoint.com/asp.net_core/asp.net_core_dbcontext.htm

    The short answer to your question is:
    You can’t or is not good idea (if you finds a way) making two connections to the same database by using EntityFrameWork Core.

    You can read also the comments here for multiple connections Two Connections For the same DataBase EntityFrameWork Core

    Login or Signup to reply.
  2. By hovering over the AddDbContext method you can see the following:
    enter image description here

    The default it’s scoped.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search