D
D
Dmitry2016-05-04 02:12:39
ASP.NET
Dmitry, 2016-05-04 02:12:39

How to work with context in Entity Framework?

Hello! Tell me how to work more correctly with the context in EF
1) do I need to create a new context object for each new request, and then destroy it?
2) Should the request be surrounded by a try-catch block?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
VanKrock, 2016-05-04
@VanKrock

It is best to use IoC containers, which will manage the lifetime of the context. But if you do not use containers, then it is better to create a context for a transaction.

T
Tsiren Naimanov, 2016-05-04
@ImmortalCAT

Creating a context is not that difficult and does not consume a lot of resources.
Another matter when the context stores in itself a DB. That is, the site caches the database into itself in order to increase speed and response.
I usually use the context per controller, not per transaction, I write the usual private MYDBCN mydb{get;set;}
and
protected override Dispose(bool dispose)
{
mydb.Dispose();
}

S
Sergey, 2016-05-04
@senal

Usually, each request creates its own context. Because, firstly, web applications usually do not store state (stateless), and secondly, EF Context is not designed for caching, and with an increase in the number of entities in the context, it starts to slow down.
I think it makes no sense to surround all try-catch, it's better to make good custom error pages.

A
AxisPod, 2016-05-04
@AxisPod

Dig towards the UnitOfWork design pattern.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question