J. Doe
J. Doe

Reputation: 91

Proper work with Entity Framework in Highly Loaded Web Applications

Generally the work with EF for an looks like this:

Some Web controller calls for a method that has something like this:

using (var ctx = new EntityContext())
{
    ...
    return something;
}

But I guess that in highly loaded application, that has several thousand requests per minute, it might create the problems. So my question is: maybe it makes sense to manually open connection and keep it alive? If yes, can anybody share the proper piece of code for such the task?

Thanks in advance

Upvotes: 1

Views: 61

Answers (2)

ken2k
ken2k

Reputation: 48975

No, don't try to keep opened connections alive. It just won't work, see https://stackoverflow.com/a/9416275/870604.

You're building an ASP.Net MVC application, so the pattern to follow to work with Entity Framework is quite simple in this use case: instantiate a new context for each new controller instance (for example using dependency injection). As a new controller instance is created for each user request, you'll have one new fresh EF context for each request, which is highly desirable.

Don't worry about creating a lot of context instances, it won't create a new DB connection each time thanks to connection pooling.

If you want your application to be scalable, your best option is to also use the async pattern if your version of Entity Framework supports it. See http://blogs.msdn.com/b/webdev/archive/2013/09/18/scaffolding-asynchronous-mvc-and-web-api-controllers-for-entity-framework-6.aspx

EDIT: Have a look to this overview of the unit of work pattern with ASP.Net MVC and EF.

Upvotes: 3

Nat
Nat

Reputation: 1

After closing tag of using element, it automatically close the connection. So you don't want to worry about it. But if you really want to open connection manually, try following (I couldn't test it. May be you need to give connection settings).

ctx.Database.Connection.Open();

Upvotes: 0

Related Questions