2013-11-11 7 views
1

Я хотел использовать объект контекста инфраструктуры объекта каждый раз. Что может быть лучшим способом определить в asp.net?Лучший способ определения объекта контекста

например:

using(employeeEntities context = new employeeEntities()) 
    { 

    } 

Я хочу использовать этот контекст, где каждый без повторного использования using

+0

Связанный: [Entity Framework 4 ObjectContext Lifetime] (http://stackoverflow.com/q/3362280/87698) – Heinzi

+0

Пожалуйста, определите всюду? Везде в классе? В вашем проекте? – Marco

ответ

2

В то время как вы можете сделать это Microsoft рекомендует использовать контекст по-другому, посмотрите на documentation :

... 
The lifetime of the ObjectContext begins when the instance is created and ends when the instance is either disposed or garbage-collected. Use using if you want all the resources that the context controls to be disposed at the end of the block. When you use using, the compiler creates a try/finally block and calls dispose in the finally block. Here are some general guidelines when deciding on the lifetime of the object context: 

1. When working with long-running object context consider the following: 
- As you load more objects and their references into memory, the object 
    context may grow quickly in memory consumption. This may cause 

    performance issues. 
- Remember to dispose of the context when it is no longer required. 
- If an exception caused the object context to be in an unrecoverable 
    state, the whole application may terminate. 
- The chances of running into concurrency-related issues increase as 
    the gap between the time when the data is queried and updated grows. 

2. When working with Web applications, **use an object context instance per request**... 

3. When working with Windows Presentation Foundation (WPF) or Windows Forms, use an object context instance per form. This lets you use change tracking functionality that object context provides. 
... 

Кроме того, посмотрите на этой связанной теме: One DbContext per web request... why?

0

Если вы просто хотите, чтобы некоторые синтаксического сахара, чтобы избежать использования using, но по-прежнему создает новый контекст каждый раз, вы можете написать некоторые методы расширения, которые помогут вам писать код, как это:

// Execute is the extension method which takes the code 
// in the using block as a delegate 
SomeEntities.Execute(context => 
    context.SomeTable.Where(item => item.Ammount > 100)); 

Я могу поделиться вам кода, если это то, что вы хотите. Обратите внимание на ответ CloudMarble, если вы хотите использовать один контекст все время.

Смежные вопросы