更好的定义Context对象的方法

时间:2013-11-11 06:54:10

标签: c# asp.net entity-framework

我想每次都使用实体框架上下文对象。 什么是在asp.net中定义的更好方法?

前:

using(employeeEntities context = new employeeEntities ())
    {

    }

我想在不重用using

的情况下使用此上下文

2 个答案:

答案 0 :(得分:2)

虽然你可以这样做,但微软建议以不同的方式使用上下文,看看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?

答案 1 :(得分: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));

如果这就是您想要的,我可以与您分享代码。如果您想一直使用单个上下文,请参阅CloudyMarble的答案。