0

How can I use same connection for two Query in EF, for example I wrote this code in MVC controller:

    DataLayer.Context context = new DataLayer.Context();

    [ChildActionOnly]
    public int TodayVisits()
    {
        return Repository.VisitsRepository.TodayVisits(context);
    }

    [ChildActionOnly]
    public int LastMonthVisits()
    {
        return Repository.VisitsRepository.LastMonthVisits(context);
    }

I'm checking output T-SQL with an application and it shows me that connection 2 time was opened.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Saeed Hamed
  • 732
  • 2
  • 10
  • 28

1 Answers1

2

For each request from your browser the a controller instance will be created.. So it will create new context for each request as well. And read this too, What is the 'page lifecycle' of an ASP.NET MVC page.

Further more creating an instance of DbContext for each request is the common practice for entity framework.

Edit..
If you need to handle the connection you need to pass the connection to the DbContext constructor and set contextOwnsConnection=false. See the documentation and try it.. Read more here..DbContext won't keep connection open for re-use

Community
  • 1
  • 1
Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92
  • As you see I have 2 method that are ChildActionOnly. I want to use once opened connection in each request, I call these actions in same request but I monitored two opened connections. – Saeed Hamed Jul 08 '13 at 09:42